Loading...
Searching...
No Matches
ManifoldEnergyForceKernel.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
6
7#include <algorithm>
8#include <array>
9#include <cmath>
10#include <stdexcept>
11#include <string>
12#include <type_traits>
13#include <utility>
14
18#include "../ml/PhaseTimers.h"
19
20namespace gpr {
21
22namespace {
23
24struct CompensatedSum {
25 double sum = 0.0;
26 double correction = 0.0;
27
28 void add(double value)
29 {
30 const double next = sum + value;
31 // TwoSum recovers the rounding error without an operand-size branch.
32 const double recovered_value = next - sum;
33 correction +=
34 (sum - (next - recovered_value)) + (value - recovered_value);
35 sum = next;
36 }
37};
38
39template <typename Left, typename Right>
40CompensatedSum compensatedProductSum(const Eigen::MatrixBase<Left>& left,
41 const Eigen::MatrixBase<Right>& right)
42{
43 CompensatedSum result;
44 for (Eigen::Index column = 0; column < left.cols(); ++column)
45 for (Eigen::Index row = 0; row < left.rows(); ++row)
46 result.add(left(row, column) * right(row, column));
47 return result;
48}
49
50void requirePositiveFinite(double value, const char* name)
51{
52 if (!(value > 0.0) || !std::isfinite(value)) {
53 throw std::invalid_argument(std::string(name) +
54 " must be positive and finite");
55 }
56}
57
58} // namespace
59
61 std::shared_ptr<const geometry::CoordinateChart> chart,
62 double magnitude_variance, double length_scale)
63 : chart_(std::move(chart))
64{
65 if (!chart_ || !chart_->valid()) {
66 throw std::invalid_argument(
67 "manifold energy-force kernel requires a valid chart");
68 }
69 setMagnitudeVariance(magnitude_variance);
70 setLengthScale(length_scale);
71 if (dynamic_cast<const geometry::AffineCoordinateChart*>(chart_.get())) {
72 const Eigen::MatrixXd jacobian = chart_->jacobian(chart_->anchor());
73 const Eigen::Index dimensions = jacobian.cols();
74 affine_metric_.resize(dimensions, dimensions);
75 for (Eigen::Index b = 0; b < dimensions; ++b)
76 for (Eigen::Index c = 0; c < dimensions; ++c)
77 affine_metric_(c, b) = jacobian.col(c).dot(jacobian.col(b));
78 }
79}
80
82{
83 requirePositiveFinite(value, "kernel magnitude variance");
84 magnitude_variance_ = value;
85}
86
88{
89 requirePositiveFinite(value, "kernel length scale");
90 length_scale_ = value;
91}
92
93void ManifoldEnergyForceKernel::validateChannel(Eigen::Index channel,
94 Eigen::Index dimensions) const
95{
96 if (channel < -1 || channel >= dimensions) {
97 throw std::invalid_argument(
98 "manifold covariance channel is outside the geometry dimension");
99 }
100}
101
102std::vector<ManifoldEnergyForceKernel::ChartPoint>
103ManifoldEnergyForceKernel::evaluatePoints(
104 const Eigen::MatrixXd& positions) const
105{
106 const Eigen::Index dimensions = chart_->anchor().size();
107 if (positions.cols() != dimensions || !positions.allFinite()) {
108 throw std::invalid_argument(
109 "manifold covariance positions have invalid shape or values");
110 }
111 std::vector<ChartPoint> points;
112 points.reserve(static_cast<std::size_t>(positions.rows()));
113 for (Eigen::Index row = 0; row < positions.rows(); ++row) {
114 const Eigen::VectorXd x = positions.row(row).transpose();
115 ChartPoint point{chart_->coordinates(x), chart_->jacobian(x)};
116 if (point.coordinates.size() != chart_->rank() ||
117 point.jacobian.rows() != chart_->rank() ||
118 point.jacobian.cols() != dimensions ||
119 !point.coordinates.allFinite() || !point.jacobian.allFinite()) {
120 throw std::runtime_error(
121 "internal coordinate chart evaluation is invalid");
122 }
123 points.push_back(std::move(point));
124 }
125 return points;
126}
127
128double ManifoldEnergyForceKernel::covariance(const ChartPoint& left,
129 const ChartPoint& right,
130 Eigen::Index left_channel,
131 Eigen::Index right_channel) const
132{
133 const Eigen::VectorXd delta = left.coordinates - right.coordinates;
134 const double a = 1.0 / (length_scale_ * length_scale_);
135 const double r2 = delta.squaredNorm();
136 const double kernel = magnitude_variance_ * std::exp(-0.5 * a * r2);
137 const double left_delta =
138 left_channel < 0 ? 0.0 : left.jacobian.col(left_channel).dot(delta);
139 const double right_delta =
140 right_channel < 0 ? 0.0 : right.jacobian.col(right_channel).dot(delta);
141 const double tangent_inner =
142 left_channel < 0 || right_channel < 0
143 ? 0.0
144 : left.jacobian.col(left_channel)
145 .dot(right.jacobian.col(right_channel));
146 return covarianceEntry(kernel, a, a * r2, left_delta, right_delta,
147 tangent_inner, left_channel, right_channel,
148 derivative_);
149}
150
151double ManifoldEnergyForceKernel::covarianceEntry(
152 double kernel, double a, double s, double left_delta, double right_delta,
153 double tangent_inner, Eigen::Index left_channel, Eigen::Index right_channel,
154 Derivative derivative)
155{
156 // With a = 1/l^2, d_L = J_L . delta, d_R = J_R . delta, t = J_L . J_R:
157 // EE = k, EG = k a d_R, GE = -k a d_L, GG = k (a t - a^2 d_L d_R).
158 // d/dlog sigma^2 multiplies every entry by 1 (the tensor itself). For
159 // d/dlog l use da/dlog l = -2a and dk/dlog l = k a r^2, which gives
160 // EE' = k a r^2, EG' = k a d_R (a r^2 - 2), GE' = -k a d_L (a r^2 - 2),
161 // GG' = k [a t (a r^2 - 2) - a^2 d_L d_R (a r^2 - 4)].
162 // Hyperparameter derivatives commute with the chart pull-back, so the
163 // same Jacobian sandwich applies to every mode.
164 // Second derivative in log l (scripts/derive_chart_second_derivatives.py):
165 // EE'' = k s (s - 2), EG'' = k a d_R (s^2 - 6 s + 4),
166 // GE'' = -k a d_L (s^2 - 6 s + 4),
167 // GG'' = k [a t (s^2 - 6 s + 4) - a^2 d_L d_R (s^2 - 10 s + 16)].
168 const bool dl = derivative == Derivative::LogLengthScale;
169 const bool dl2 = derivative == Derivative::LogLengthScale2;
170 const double q2 = s * s - 6.0 * s + 4.0;
171 if (left_channel < 0 && right_channel < 0) {
172 return dl2 ? kernel * s * (s - 2.0) : (dl ? kernel * s : kernel);
173 }
174
175 if (left_channel < 0) {
176 return kernel * a * right_delta * (dl2 ? q2 : (dl ? (s - 2.0) : 1.0));
177 }
178 if (right_channel < 0) {
179 return -kernel * a * left_delta * (dl2 ? q2 : (dl ? (s - 2.0) : 1.0));
180 }
181
182 if (dl2) {
183 return kernel *
184 (a * tangent_inner * q2 -
185 a * a * left_delta * right_delta * (s * s - 10.0 * s + 16.0));
186 }
187 if (!dl) {
188 return kernel * (a * tangent_inner - a * a * left_delta * right_delta);
189 }
190 return kernel * (a * tangent_inner * (s - 2.0) -
191 a * a * left_delta * right_delta * (s - 4.0));
192}
193
195 const Eigen::MatrixXd& left_positions,
196 const Eigen::MatrixXd& right_positions, Eigen::Index left_channel,
197 Eigen::Index right_channel) const
198{
199 const Eigen::Index dimensions = chart_->anchor().size();
200 validateChannel(left_channel, dimensions);
201 validateChannel(right_channel, dimensions);
202 const auto left = evaluatePoints(left_positions);
203 const auto right = evaluatePoints(right_positions);
204 Eigen::MatrixXd block(left_positions.rows(), right_positions.rows());
205 for (Eigen::Index i = 0; i < block.rows(); ++i) {
206 for (Eigen::Index j = 0; j < block.cols(); ++j) {
207 block(i, j) = covariance(left[static_cast<std::size_t>(i)],
208 right[static_cast<std::size_t>(j)],
209 left_channel, right_channel);
210 }
211 }
212 return block;
213}
214
216 const Eigen::MatrixXd& positions) const
217{
218 const Eigen::Index dimensions = chart_->anchor().size();
219 const auto points = evaluatePoints(positions);
220 return assembleJointEnergyGradientCovariance(points, points, dimensions,
223}
224
226 const Eigen::MatrixXd& left_positions,
227 const Eigen::MatrixXd& right_positions) const
228{
229 const Eigen::Index dimensions = chart_->anchor().size();
230 const auto left = evaluatePoints(left_positions);
231 const auto right = evaluatePoints(right_positions);
232 return assembleJointEnergyGradientCovariance(left, right, dimensions,
235}
236
238 const Eigen::MatrixXd& positions, const linalg::MpiContext& context,
239 const linalg::LocalExecutor& execution) const
240{
241 std::array<Eigen::MatrixXd, 1> result;
242 linalg::assembleCollectively(context, result, [&] {
243 const auto points = evaluatePoints(positions);
244 result.front() = assembleJointEnergyGradientCovariance(
245 points, points, chart_->anchor().size(), context, execution);
246 });
247 return std::move(result.front());
248}
249
252 const Eigen::MatrixXd& positions) const
253{
254 return [kernel = *this, points = evaluatePoints(positions)](
255 Eigen::Index i, Eigen::Index j) -> Eigen::MatrixXd {
256 const auto rows = static_cast<Eigen::Index>(points.size());
257 if (i < 0 || j < 0 || i >= rows || j >= rows)
258 throw std::out_of_range("chart covariance tile index is invalid");
259 const std::span<const ChartPoint> span(points);
260 return kernel.assembleJointEnergyGradientCovariance(
261 span.subspan(i, 1), span.subspan(j, 1),
262 kernel.chart_->anchor().size(), linalg::MpiContext::local(),
264 };
265}
266
267Eigen::MatrixXd
268ManifoldEnergyForceKernel::assembleJointEnergyGradientCovariance(
269 std::span<const ChartPoint> left, std::span<const ChartPoint> right,
270 Eigen::Index dimensions, const linalg::MpiContext& context,
271 const linalg::LocalExecutor& execution) const
272{
273 const Eigen::Index n_left = static_cast<Eigen::Index>(left.size());
274 const Eigen::Index n_right = static_cast<Eigen::Index>(right.size());
275 Eigen::MatrixXd result = Eigen::MatrixXd::Zero(n_left * (dimensions + 1),
276 n_right * (dimensions + 1));
277 visitJointEnergyGradientCovariance(
278 left, right, dimensions, context, execution,
279 [&](std::size_t, Eigen::Index row, Eigen::Index col, double value) {
280 result(row, col) = value;
281 });
282 return result;
283}
284
285template <typename Entry>
286void ManifoldEnergyForceKernel::visitJointEnergyGradientCovariance(
287 std::span<const ChartPoint> left, std::span<const ChartPoint> right,
288 Eigen::Index dimensions, const linalg::MpiContext& context,
289 const linalg::LocalExecutor& execution, const Entry& entry) const
290{
291 const Eigen::Index n_left = static_cast<Eigen::Index>(left.size());
292 const Eigen::Index n_right = static_cast<Eigen::Index>(right.size());
293 const double a = 1.0 / (length_scale_ * length_scale_);
294 // An affine chart has a constant Jacobian. The cached metric serves all
295 // distributed observation tiles and every hyperparameter derivative;
296 // each entry retains covarianceBlock's scalar contraction order.
297 const std::size_t pairs = left.size() * right.size();
298 const auto rank = static_cast<std::size_t>(context.rank);
299 const auto ranks = static_cast<std::size_t>(context.nprocs);
300 const std::size_t owned = rank < pairs ? 1 + (pairs - 1 - rank) / ranks : 0;
301 const auto workers =
302 std::min(owned, static_cast<std::size_t>(execution.concurrency()));
303 PhaseTimers::chart_assembly_tiles.fetch_add(owned,
304 std::memory_order_relaxed);
305 execution.forEach(workers, [&](std::size_t worker) {
306 Eigen::VectorXd left_delta(dimensions), right_delta(dimensions);
307 for (std::size_t local = worker; local < owned; local += workers) {
308 const std::size_t pair = rank + local * ranks;
309 const Eigen::Index i =
310 static_cast<Eigen::Index>(pair % left.size());
311 const Eigen::Index j =
312 static_cast<Eigen::Index>(pair / left.size());
313 const auto& right_point = right[static_cast<std::size_t>(j)];
314 const auto& left_point = left[static_cast<std::size_t>(i)];
315 const Eigen::VectorXd delta =
316 left_point.coordinates - right_point.coordinates;
317 const double r2 = delta.squaredNorm();
318 const double kernel = magnitude_variance_ * std::exp(-0.5 * a * r2);
319 const double s = a * r2;
320 const auto emit = [&](Eigen::Index row, Eigen::Index col, double dl,
321 double dr, double tangent, Eigen::Index c,
322 Eigen::Index b) {
323 if constexpr (std::is_invocable_v<Entry, std::size_t,
324 Eigen::Index, Eigen::Index,
325 double, double>) {
326 entry(worker, row, col,
327 covarianceEntry(kernel, a, s, dl, dr, tangent, c, b,
329 covarianceEntry(kernel, a, s, dl, dr, tangent, c, b,
331 } else {
332 entry(worker, row, col,
333 covarianceEntry(kernel, a, s, dl, dr, tangent, c, b,
334 derivative_));
335 }
336 };
337 // One geometry pair supplies all observation channels. Scalar
338 // contractions preserve the block evaluator's accumulation order.
339 for (Eigen::Index channel = 0; channel < dimensions; ++channel) {
340 left_delta(channel) =
341 left_point.jacobian.col(channel).dot(delta);
342 right_delta(channel) =
343 right_point.jacobian.col(channel).dot(delta);
344 }
345 emit(i, j, 0.0, 0.0, 0.0, -1, -1);
346 for (Eigen::Index channel = 0; channel < dimensions; ++channel) {
347 emit((channel + 1) * n_left + i, j, left_delta(channel), 0.0,
348 0.0, channel, -1);
349 emit(i, (channel + 1) * n_right + j, 0.0, right_delta(channel),
350 0.0, -1, channel);
351 }
352 for (Eigen::Index b = 0; b < dimensions; ++b)
353 for (Eigen::Index c = 0; c < dimensions; ++c)
354 emit((c + 1) * n_left + i, (b + 1) * n_right + j,
355 left_delta(c), right_delta(b),
356 affine_metric_.size() > 0
357 ? affine_metric_(c, b)
358 : left_point.jacobian.col(c).dot(
359 right_point.jacobian.col(b)),
360 c, b);
361 }
362 });
363}
364
366 const Eigen::MatrixXd& left_positions,
367 const Eigen::MatrixXd& right_positions, const Eigen::MatrixXd& weight,
368 const linalg::MpiContext& context,
369 const linalg::LocalExecutor& execution) const
370{
371 std::array<Eigen::MatrixXd, 2> pair_terms{
372 Eigen::MatrixXd::Zero(left_positions.rows(), right_positions.rows()),
373 Eigen::MatrixXd::Zero(left_positions.rows(), right_positions.rows())};
374 linalg::assembleCollectively(context, pair_terms, [&] {
375 const Eigen::Index dimensions = chart_->anchor().size();
376 if (weight.rows() != left_positions.rows() * (dimensions + 1) ||
377 weight.cols() != right_positions.rows() * (dimensions + 1) ||
378 !weight.allFinite())
379 throw std::invalid_argument("invalid joint covariance weight");
380 if (left_positions.rows() == 0 || right_positions.rows() == 0) return;
381 const auto left = evaluatePoints(left_positions);
382 const auto right = evaluatePoints(right_positions);
383 const Eigen::Index n_left = left_positions.rows();
384 const Eigen::Index n_right = right_positions.rows();
385 visitJointEnergyGradientCovariance(
386 left, right, dimensions, context, execution,
387 [&](std::size_t, Eigen::Index row, Eigen::Index col, double value) {
388 const Eigen::Index i = row % n_left;
389 const Eigen::Index j = col % n_right;
390 linalg::CompensatedSum partial{pair_terms[0](i, j),
391 pair_terms[1](i, j)};
392 partial.add(weight(row, col) * value);
393 pair_terms[0](i, j) = partial.sum;
394 pair_terms[1](i, j) = partial.corr;
395 });
396 });
398 for (Eigen::Index j = 0; j < pair_terms[0].cols(); ++j)
399 for (Eigen::Index i = 0; i < pair_terms[0].rows(); ++i) {
400 total.add(pair_terms[0](i, j));
401 total.add(pair_terms[1](i, j));
402 }
403 return total.value();
404}
405
408 const Eigen::MatrixXd& positions, const linalg::MpiContext& context,
409 const linalg::LocalExecutor& execution) const
410{
411 std::vector<ChartPoint> points;
412 std::array<Eigen::MatrixXd, 0> no_tensors;
413 linalg::assembleCollectively(context, no_tensors,
414 [&] { points = evaluatePoints(positions); });
415 return [kernel = *this, points = std::move(points), context, execution](
416 Eigen::Index first, const Eigen::MatrixXd& weight,
418 const Eigen::Index dimensions = kernel.chart_->anchor().size();
419 const Eigen::Index channels = dimensions + 1;
420 const Eigen::Index rows = static_cast<Eigen::Index>(points.size());
421 std::array<Eigen::MatrixXd, 2> pair_terms;
422 linalg::assembleCollectively(context, pair_terms, [&] {
423 if (first < 0 || first > rows || weight.rows() % channels != 0 ||
424 weight.rows() / channels > rows - first ||
425 weight.cols() != rows * channels || !weight.allFinite())
426 throw std::invalid_argument(
427 "invalid prepared covariance weight");
428 const auto count =
429 static_cast<std::size_t>(weight.rows() / channels);
430 const Eigen::Index n_left = static_cast<Eigen::Index>(count);
431 for (auto& terms: pair_terms)
432 terms = Eigen::MatrixXd::Zero(n_left, rows);
433 if (n_left == 0 || rows == 0) return;
434 const std::span<const ChartPoint> all(points);
435 auto selected = kernel;
436 selected.setDerivative(derivative);
437 selected.visitJointEnergyGradientCovariance(
438 all.subspan(static_cast<std::size_t>(first), count), all,
439 dimensions, context, execution,
440 [&](std::size_t, Eigen::Index row, Eigen::Index col,
441 double value) {
442 const Eigen::Index i = row % n_left;
443 const Eigen::Index j = col % rows;
444 linalg::CompensatedSum partial{pair_terms[0](i, j),
445 pair_terms[1](i, j)};
446 partial.add(weight(row, col) * value);
447 pair_terms[0](i, j) = partial.sum;
448 pair_terms[1](i, j) = partial.corr;
449 });
450 });
452 for (Eigen::Index j = 0; j < pair_terms[0].cols(); ++j)
453 for (Eigen::Index i = 0; i < pair_terms[0].rows(); ++i) {
454 total.add(pair_terms[0](i, j));
455 total.add(pair_terms[1](i, j));
456 }
457 return total.value();
458 };
459}
460
461Eigen::Vector2d
463 const Eigen::MatrixXd& positions, const JointWeightRows& weight_rows,
464 const linalg::MpiContext& context,
465 const linalg::LocalExecutor& execution) const
466{
467 Eigen::MatrixXd contributions;
468 std::array<Eigen::MatrixXd, 0> no_tensors;
469 linalg::assembleCollectively(context, no_tensors, [&] {
470 if (!weight_rows || context.nprocs <= 0 || context.rank < 0 ||
471 context.rank >= context.nprocs)
472 throw std::invalid_argument("invalid joint contraction ownership");
473 const auto points = evaluatePoints(positions);
474 const std::span<const ChartPoint> all(points);
475 const auto local = linalg::MpiContext::local();
476 const linalg::LocalExecutor serial(1);
477 const Eigen::Index rows = positions.rows();
478 const Eigen::Index channels = positions.cols() + 1;
479 contributions = Eigen::MatrixXd::Zero(rows, 4);
480 const Eigen::Index first_owned = rows * context.rank / context.nprocs;
481 const Eigen::Index end_owned =
482 rows * (context.rank + 1) / context.nprocs;
483 constexpr Eigen::Index batch_rows = 16;
484 for (Eigen::Index first = first_owned; first < end_owned;
485 first += batch_rows) {
486 const Eigen::Index count = std::min(batch_rows, end_owned - first);
487 const Eigen::MatrixXd weight = weight_rows(first, count);
488 if (weight.rows() != count * channels ||
489 weight.cols() != rows * channels || !weight.allFinite())
490 throw std::invalid_argument("invalid joint contraction rows");
491 // Each geometry owns its complete column traversal. Neither rank
492 // nor thread partitioning changes the order of its products.
493 execution.forEach(
494 static_cast<std::size_t>(count), [&](std::size_t offset) {
495 const auto row = static_cast<Eigen::Index>(offset);
496 CompensatedSum magnitude, length;
497 visitJointEnergyGradientCovariance(
498 all.subspan(static_cast<std::size_t>(first + row), 1),
499 all, positions.cols(), local, serial,
500 [&](std::size_t, Eigen::Index channel, Eigen::Index col,
501 double dm, double dl) {
502 const double w = weight(channel * count + row, col);
503 magnitude.add(w * dm);
504 length.add(w * dl);
505 });
506 contributions.row(first + row) << magnitude.sum,
507 magnitude.correction, length.sum, length.correction;
508 });
509 }
510 });
511 // One rank contributes to each row. Preserve the compensation through
512 // communication, then combine rows in their common geometry order.
513 linalg::ordered_sum_bcast(contributions.data(), contributions.size(),
514 context);
515 Eigen::Vector2d result;
516 for (Eigen::Index parameter = 0; parameter < 2; ++parameter) {
517 CompensatedSum total;
518 for (Eigen::Index row = 0; row < contributions.rows(); ++row) {
519 total.add(contributions(row, 2 * parameter));
520 total.add(contributions(row, 2 * parameter + 1));
521 }
522 result(parameter) = total.sum + total.correction;
523 }
524 return result;
525}
526
527Eigen::Vector2d
529 const Eigen::MatrixXd& positions, const JointWeightRows& left_factors,
530 const JointWeightRows& right_factors, const linalg::MpiContext& context,
531 const linalg::LocalExecutor& execution) const
532{
533 struct ProjectedFactor {
534 Eigen::VectorXd energy;
535 Eigen::MatrixXd gradient;
536 };
537 Eigen::MatrixXd contributions;
538 std::array<Eigen::MatrixXd, 0> no_tensors;
539 linalg::assembleCollectively(context, no_tensors, [&] {
540 if (affine_metric_.size() == 0)
541 throw std::invalid_argument(
542 "factored contraction requires an affine chart");
543 if (!left_factors || !right_factors || context.nprocs <= 0 ||
544 context.rank < 0 || context.rank >= context.nprocs)
545 throw std::invalid_argument(
546 "invalid factored contraction ownership");
547 const auto points = evaluatePoints(positions);
548 const Eigen::Index rows = positions.rows();
549 const Eigen::Index dimensions = positions.cols();
550 const Eigen::Index first_owned = rows * context.rank / context.nprocs;
551 const Eigen::Index end_owned =
552 rows * (context.rank + 1) / context.nprocs;
553 const Eigen::Index owned = end_owned - first_owned;
554 contributions = Eigen::MatrixXd::Zero(rows, 4);
555 if (!owned) return;
556 Eigen::Index factor_columns = -1;
557 const auto project = [&](const JointWeightRows& factors,
558 Eigen::Index row) {
559 const Eigen::MatrixXd factor = factors(row, 1);
560 if (factor.rows() != dimensions + 1 ||
561 (factor_columns >= 0 && factor.cols() != factor_columns) ||
562 !factor.allFinite())
563 throw std::invalid_argument("invalid joint weight factor rows");
564 factor_columns = factor.cols();
565 ProjectedFactor result;
566 result.energy = factor.row(0).transpose();
567 result.gradient.noalias() =
568 points[static_cast<std::size_t>(row)].jacobian *
569 factor.bottomRows(dimensions);
570 return result;
571 };
572 std::vector<ProjectedFactor> left;
573 left.reserve(static_cast<std::size_t>(owned));
574 for (Eigen::Index row = first_owned; row < end_owned; ++row)
575 left.push_back(project(left_factors, row));
576 std::vector<std::array<CompensatedSum, 2>> sums(
577 static_cast<std::size_t>(owned));
578 const double a = 1.0 / (length_scale_ * length_scale_);
579 constexpr Eigen::Index batch_rows = 16;
581 static_cast<std::size_t>(owned * rows), std::memory_order_relaxed);
582 for (Eigen::Index first = 0; first < rows; first += batch_rows) {
583 const Eigen::Index count = std::min(batch_rows, rows - first);
584 std::vector<ProjectedFactor> right;
585 right.reserve(static_cast<std::size_t>(count));
586 for (Eigen::Index row = first; row < first + count; ++row)
587 right.push_back(project(right_factors, row));
588 execution.forEach(
589 static_cast<std::size_t>(owned), [&](std::size_t offset) {
590 const Eigen::Index i =
591 first_owned + static_cast<Eigen::Index>(offset);
592 const auto& l = left[offset];
593 auto& magnitude = sums[offset][0];
594 auto& length = sums[offset][1];
595 Eigen::VectorXd p(factor_columns), z(factor_columns);
596 for (Eigen::Index row = 0; row < count; ++row) {
597 const Eigen::Index j = first + row;
598 const auto& r = right[static_cast<std::size_t>(row)];
599 const Eigen::VectorXd delta =
600 points[static_cast<std::size_t>(i)].coordinates -
601 points[static_cast<std::size_t>(j)].coordinates;
602 const double r2 = delta.squaredNorm();
603 const double kernel =
604 magnitude_variance_ * std::exp(-0.5 * a * r2);
605 const double s = a * r2;
606 p.noalias() = l.gradient.transpose() * delta;
607 z.noalias() = r.gradient.transpose() * delta;
608 const auto ee =
609 compensatedProductSum(l.energy, r.energy);
610 const auto eg = compensatedProductSum(l.energy, z);
611 const auto ge = compensatedProductSum(p, r.energy);
612 const auto gg =
613 compensatedProductSum(l.gradient, r.gradient);
614 const auto outer = compensatedProductSum(p, z);
615 const auto add = [](CompensatedSum& target,
616 const CompensatedSum& value,
617 const auto& scale) {
618 target.add(scale(value.sum));
619 target.add(scale(value.correction));
620 };
621 // The factor contraction keeps each differential block:
622 // EE, EG, GE, the chart metric and the directional
623 // product. Scaling from the weight inward avoids
624 // forming a^2 first.
625 add(magnitude, ee,
626 [&](double x) { return kernel * x; });
627 add(magnitude, eg,
628 [&](double x) { return kernel * (a * x); });
629 add(magnitude, ge,
630 [&](double x) { return -kernel * (a * x); });
631 add(magnitude, gg,
632 [&](double x) { return kernel * (a * x); });
633 add(magnitude, outer,
634 [&](double x) { return -kernel * (a * (a * x)); });
635 add(length, ee,
636 [&](double x) { return kernel * (s * x); });
637 add(length, eg, [&](double x) {
638 return kernel * (a * ((s - 2.0) * x));
639 });
640 add(length, ge, [&](double x) {
641 return -kernel * (a * ((s - 2.0) * x));
642 });
643 add(length, gg, [&](double x) {
644 return kernel * (a * ((s - 2.0) * x));
645 });
646 add(length, outer, [&](double x) {
647 return -kernel * (a * (a * ((s - 4.0) * x)));
648 });
649 }
650 });
651 }
652 for (Eigen::Index offset = 0; offset < owned; ++offset) {
653 const auto& sum = sums[static_cast<std::size_t>(offset)];
654 contributions.row(first_owned + offset) << sum[0].sum,
655 sum[0].correction, sum[1].sum, sum[1].correction;
656 }
657 });
658 linalg::ordered_sum_bcast(contributions.data(), contributions.size(),
659 context);
660 Eigen::Vector2d result;
661 for (Eigen::Index parameter = 0; parameter < 2; ++parameter) {
662 CompensatedSum total;
663 for (Eigen::Index row = 0; row < contributions.rows(); ++row) {
664 total.add(contributions(row, 2 * parameter));
665 total.add(contributions(row, 2 * parameter + 1));
666 }
667 result(parameter) = total.sum + total.correction;
668 }
669 return result;
670}
671
673 const Eigen::MatrixXd& positions) const
674{
675 Eigen::MatrixXd result = jointEnergyGradientCovariance(positions);
676 const Eigen::Index n = positions.rows();
677 const Eigen::Index energy_channels = n;
678 if (result.rows() > energy_channels) {
679 result.block(energy_channels, 0, result.rows() - energy_channels,
680 result.cols()) *= -1.0;
681 result.block(0, energy_channels, result.rows(),
682 result.cols() - energy_channels) *= -1.0;
683 }
684 return result;
685}
686
687} // namespace gpr
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
Eigen::Vector2d contractJointLogHyperparameterDerivatives(const Eigen::MatrixXd &positions, const JointWeightRows &weight_rows, const linalg::MpiContext &context, const linalg::LocalExecutor &execution) const
JointCovarianceTileFunction prepareJointCovarianceTiles(const Eigen::MatrixXd &positions) const
double contractJointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, const Eigen::MatrixXd &weight, const linalg::MpiContext &context, const linalg::LocalExecutor &execution) const
const geometry::CoordinateChart & chart() const
Eigen::MatrixXd covarianceBlock(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions, Eigen::Index left_channel, Eigen::Index right_channel) const
JointContraction prepareJointContraction(const Eigen::MatrixXd &positions, const linalg::MpiContext &context, const linalg::LocalExecutor &execution) const
ManifoldEnergyForceKernel(std::shared_ptr< const geometry::CoordinateChart > chart, double magnitude_variance, double length_scale)
Derivative derivative() const noexcept
Eigen::MatrixXd jointEnergyForceCovariance(const Eigen::MatrixXd &positions) const
Joint covariance in physical order [E; F_col0; ...; F_colD-1].
std::function< Eigen::MatrixXd(Eigen::Index, Eigen::Index)> JointCovarianceTileFunction
Eigen::MatrixXd jointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions) const
std::function< Eigen::MatrixXd(Eigen::Index, Eigen::Index)> JointWeightRows
Eigen::MatrixXd jointEnergyGradientCovariance(const Eigen::MatrixXd &positions) const
Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
std::function< double(Eigen::Index, const Eigen::MatrixXd &, Derivative)> JointContraction
void forEach(std::size_t count, Operation &&operation, Grain grain=Grain::Fine) const
void ordered_sum_bcast(double *data, int count, const MpiContext &context)
void assembleCollectively(const MpiContext &context, Matrices &result, const Body &body)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
STL namespace.
static std::atomic_size_t chart_assembly_tiles
static MpiContext local() noexcept
Definition MpiContext.h:75