Loading...
Searching...
No Matches
ConditionedKernel.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3
4#include "ConditionedKernel.h"
5
6#include <Eigen/Cholesky>
7#include <algorithm>
8#include <limits>
9#include <stdexcept>
10#include <utility>
11
16#include "../ml/PhaseTimers.h"
17#ifdef GPR_LINALG_SCALAPACK
19#endif
20
21namespace gpr {
22namespace {
23Eigen::MatrixXd channelRows(const Eigen::MatrixXd& joint, Eigen::Index rows,
24 Eigen::Index channel)
25{
26 if (channel < -1 || (channel + 2) * rows > joint.rows())
27 throw std::invalid_argument("invalid conditioned covariance channel");
28 return joint.middleRows((channel + 1) * rows, rows);
29}
30
31Eigen::MatrixXd symmetric(const Eigen::MatrixXd& matrix)
32{
33 return 0.5 * (matrix + matrix.transpose());
34}
35
36Eigen::MatrixXd conditionalCovariance(const Eigen::MatrixXd& query,
37 const Eigen::MatrixXd& anchor_query,
38 const Eigen::MatrixXd& weights)
39{
40 return symmetric(query - anchor_query.transpose() * weights);
41}
42
43bool validOnAllRanks(bool valid,
44 const std::shared_ptr<linalg::DistributedState>& execution)
45{
46#ifdef GPR_LINALG_SCALAPACK
47 if (execution) {
48 if (!execution->communication()) execution->initialize();
49 const auto context = execution->communication()->view();
50 if (context.is_distributed()) {
51 int accepted = valid;
52 MPI_Allreduce(MPI_IN_PLACE, &accepted, 1, MPI_INT, MPI_MIN,
53 context.comm);
54 return accepted != 0;
55 }
56 }
57#else
58 (void)execution;
59#endif
60 return valid;
61}
62} // namespace
63
65 std::shared_ptr<const KernelOperator> kernel;
68 bool observation_major = false;
70
71 template <typename Derived>
72 Eigen::Matrix<double, Eigen::Dynamic, Derived::ColsAtCompileTime>
73 factorRows(const Eigen::MatrixBase<Derived>& right) const
74 {
75 Eigen::Matrix<double, Eigen::Dynamic, Derived::ColsAtCompileTime>
76 result(right.rows(), right.cols());
78 const Eigen::Index channels = anchors.cols() + 1;
79 for (Eigen::Index row = 0; row < right.rows(); ++row)
80 result.row(row) = right.row((row % channels) * anchors.rows() +
81 row / channels);
82 } else {
83 result = right;
84 }
85 return result;
86 }
87
88 template <typename Derived>
89 Eigen::Matrix<double, Eigen::Dynamic, Derived::ColsAtCompileTime> whiten(
90 const Eigen::MatrixBase<Derived>& right) const
91 {
92 auto result = factorRows(right);
93 lower.forwardSolveInPlace(result);
94 return result;
95 }
96
97 template <typename Derived>
98 Eigen::Matrix<double, Eigen::Dynamic, Derived::ColsAtCompileTime> solve(
99 const Eigen::MatrixBase<Derived>& right) const
100 {
101 auto result = factorRows(right);
102 lower.solveInPlace(result);
103 if (observation_major) {
104 Eigen::VectorXd ordered(result.rows());
105 const Eigen::Index channels = anchors.cols() + 1;
106 for (Eigen::Index column = 0; column < result.cols(); ++column) {
107 ordered = result.col(column);
108 for (Eigen::Index row = 0; row < result.rows(); ++row)
109 result((row % channels) * anchors.rows() + row / channels,
110 column) = ordered(row);
111 }
112 }
113 return result;
114 }
115};
116
118 std::shared_ptr<const KernelOperator> kernel, Coord anchors,
119 Eigen::VectorXd noise)
120 : state_(std::make_unique<State>())
121{
122 if (!kernel || anchors.rows() == 0 || anchors.cols() == 0 ||
123 !anchors.allFinite() ||
124 noise.size() != anchors.rows() * (anchors.cols() + 1) ||
125 !noise.allFinite() || (noise.array() < 0.0).any())
126 throw std::invalid_argument("invalid conditioned kernel anchors");
127 Eigen::MatrixXd lower = kernel->jointEnergyGradientCovariance(anchors);
128 lower.diagonal() += noise;
129 const bool factored =
132 : Eigen::LLT<Eigen::Ref<Eigen::MatrixXd>>(lower).info() ==
133 Eigen::Success;
134 if (!factored)
135 throw std::invalid_argument("conditioned kernel anchors are singular");
136 state_->lower = linalg::CholeskyPanels::fromLower(lower);
137 state_->kernel = std::move(kernel);
138 state_->anchors = std::move(anchors);
139 state_->anchor_covariance =
140 makeKernelCrossCovariance(state_->kernel, state_->anchors);
141}
142
143ConditionedKernel::ConditionedKernel(std::unique_ptr<State> state)
144 : state_(std::move(state))
145{
146}
147
149
151ConditionedKernel::prepareCrossCovariance(const Eigen::MatrixXd& training) const
152{
153 const auto& state = *state_;
154 const Eigen::MatrixXd weights =
155 state.solve(state.anchor_covariance(training).transpose());
156 return [cross = makeKernelCrossCovariance(state.kernel, training),
157 anchors = state.anchor_covariance,
158 weights](const Eigen::MatrixXd& query) -> Eigen::MatrixXd {
159 return cross(query) - anchors(query) * weights;
160 };
161}
162
164 const Eigen::MatrixXd& left, const Eigen::MatrixXd& right) const
165{
166 if (detail::matrixExactlyEqual(left, right))
168 const auto& state = *state_;
169 const Eigen::MatrixXd la = state.anchor_covariance(left);
170 const Eigen::MatrixXd ar = state.anchor_covariance(right).transpose();
171 return state.kernel->jointEnergyGradientCrossCovariance(left, right) -
172 la * state.solve(ar);
173}
174
176 const Eigen::MatrixXd& positions) const
177{
178 const auto& state = *state_;
179 const Eigen::MatrixXd anchor_query =
180 state.anchor_covariance(positions).transpose();
181 const Eigen::MatrixXd weights = state.solve(anchor_query);
182 return conditionalCovariance(
183 state.kernel->jointEnergyGradientCovariance(positions), anchor_query,
184 weights);
185}
186
188 const Eigen::MatrixXd& positions) const
189{
190 const auto& state = *state_;
191 const Eigen::MatrixXd anchor_query =
192 state.anchor_covariance(positions).transpose();
193 const Eigen::MatrixXd weights = state.solve(anchor_query);
194 return state.kernel->jointEnergyGradientDiagonal(positions) -
195 (anchor_query.array() * weights.array())
196 .colwise()
197 .sum()
198 .transpose()
199 .matrix();
200}
201
203 const Eigen::MatrixXd& left, const Eigen::MatrixXd& right,
204 Eigen::Index left_channel, Eigen::Index right_channel) const
205{
206 const auto& state = *state_;
207 const Eigen::MatrixXd la =
208 channelRows(state.anchor_covariance(left), left.rows(), left_channel);
209 const Eigen::MatrixXd ra = channelRows(state.anchor_covariance(right),
210 right.rows(), right_channel);
211 return state.kernel->covarianceBlock(left, right, left_channel,
212 right_channel) -
213 la * state.solve(ra.transpose());
214}
215
217 const Eigen::MatrixXd& left, const Eigen::MatrixXd& right,
218 const Eigen::VectorXd& weights) const
219{
220 return prepareMean(right, weights)(left);
221}
222
224 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
225{
226 const auto [positions, combined] = meanExpansion(training, weights);
227 return makeKernelMean(state_->kernel, positions, combined);
228}
229
231 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
232{
233 const auto [positions, combined] = meanExpansion(training, weights);
234 return makeAnalyticKernelMeanHessianVector(state_->kernel, positions,
235 combined);
236}
237
239 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
240{
241 // Exact only when the child prepares its own Hessian. The generic
242 // wrapper is not an analytic contraction.
243 const auto [positions, combined] = meanExpansion(training, weights);
244 return state_->kernel->prepareMeanHessian(positions, combined);
245}
246
247const std::shared_ptr<const KernelOperator>& ConditionedKernel::childKernel()
248 const noexcept
249{
250 return state_->kernel;
251}
252
253std::pair<Coord, Eigen::VectorXd> ConditionedKernel::meanExpansion(
254 const Eigen::MatrixXd& training, const Eigen::VectorXd& weights) const
255{
256 const auto& state = *state_;
257 if (training.cols() != state.anchors.cols() ||
258 weights.size() != training.rows() * (training.cols() + 1) ||
259 !training.allFinite() || !weights.allFinite())
260 throw std::invalid_argument("invalid conditioned mean training data");
261 const Eigen::VectorXd anchor_weights =
262 state.solve(state.kernel->applyJointCrossCovariance(state.anchors,
263 training, weights));
264 const Eigen::Index rows = training.rows() + state.anchors.rows();
265 Eigen::MatrixXd positions(rows, training.cols());
266 positions.topRows(training.rows()) = training;
267 positions.bottomRows(state.anchors.rows()) = state.anchors;
268 Eigen::VectorXd combined(rows * (training.cols() + 1));
269 for (Eigen::Index channel = 0; channel <= training.cols(); ++channel) {
270 combined.segment(channel * rows, training.rows()) =
271 weights.segment(channel * training.rows(), training.rows());
272 combined.segment(channel * rows + training.rows(),
273 state.anchors.rows()) =
274 -anchor_weights.segment(channel * state.anchors.rows(),
275 state.anchors.rows());
276 }
277 return {std::move(positions), std::move(combined)};
278}
279
281 const Eigen::VectorXd& weights,
282 const Eigen::VectorXd& position,
283 const Eigen::VectorXd& direction,
284 Eigen::VectorXd& action) const
285{
286 if (auto prepare = prepareMeanHessian(training, weights)) {
287 const auto apply = prepare(position);
288 return apply && apply(direction, action);
289 }
290 const auto& state = *state_;
291 const Eigen::VectorXd anchor_weights =
292 state.solve(state.kernel->applyJointCrossCovariance(state.anchors,
293 training, weights));
294 Eigen::VectorXd correction;
295 if (!state.kernel->meanHessianVector(training, weights, position, direction,
296 action) ||
297 !state.kernel->meanHessianVector(state.anchors, anchor_weights,
298 position, direction, correction))
299 return false;
300 action -= correction;
301 return action.allFinite();
302}
303
305{
306 return state_->kernel->meanCurvature();
307}
308
310 const Eigen::MatrixXd& joint,
311 const std::vector<Eigen::MatrixXd>& derivatives, Eigen::Index anchor_rows,
312 Eigen::Index query_rows, Eigen::Index dimensions,
313 const Eigen::VectorXd& anchor_noise, Eigen::MatrixXd& covariance,
314 std::vector<Eigen::MatrixXd>& conditional_derivatives)
315{
317 joint, derivatives, anchor_rows, query_rows, dimensions, anchor_noise,
318 covariance, conditional_derivatives, linalg::LocalExecutor{});
319}
320
322 Eigen::MatrixXd lower;
323 bool observation_major = false;
324#ifdef GPR_LINALG_SCALAPACK
325 std::unique_ptr<linalg::ScalapackPDPotrfInverse> distributed;
326#endif
327};
328
332 ConditionalKernelProjection&&) noexcept = default;
334 ConditionalKernelProjection&&) noexcept = default;
335
336template <typename Derived>
337bool ConditionalKernelProjection::prepareJoint(
338 const Eigen::MatrixBase<Derived>& joint, Eigen::Index anchor_rows,
339 Eigen::Index query_rows, Eigen::Index dimensions,
340 const Eigen::VectorXd& anchor_noise, Eigen::MatrixXd& covariance,
341 const std::shared_ptr<linalg::DistributedState>& execution)
342{
343 valid_ = false;
344 factor_.reset();
345 const Eigen::Index na = anchor_rows * (dimensions + 1);
346 const Eigen::Index nq = query_rows * (dimensions + 1);
347 if (!validOnAllRanks(
348 anchor_rows > 0 && query_rows > 0 && dimensions > 0 &&
349 joint.rows() == na + nq && joint.cols() == na + nq &&
350 joint.allFinite() && anchor_noise.size() == na &&
351 anchor_noise.allFinite() && (anchor_noise.array() >= 0.0).all(),
352 execution))
353 return false;
354 anchor_rows_ = anchor_rows;
355 query_rows_ = query_rows;
356 dimensions_ = dimensions;
357 Eigen::MatrixXd aa, aq, qq;
358 bool include_anchor = true;
360 if (execution) {
361 // Redistribution reads the dense source on the root alone. Cross
362 // and query blocks remain available for each rank's contractions.
363 execution->initialize();
364 include_anchor = execution->is_root();
365 }
366#endif
367 blocks(joint, aa, aq, qq, include_anchor);
368 return prepareBlocks(std::move(aa), aq, qq, anchor_noise, covariance,
369 execution);
370}
371
373 const Eigen::MatrixXd& joint, Eigen::Index anchor_rows,
374 Eigen::Index query_rows, Eigen::Index dimensions,
375 const Eigen::VectorXd& anchor_noise, Eigen::MatrixXd& covariance,
376 const std::shared_ptr<linalg::DistributedState>& execution)
377{
378 return prepareJoint(joint, anchor_rows, query_rows, dimensions,
379 anchor_noise, covariance, execution);
380}
381
383 const Eigen::MatrixXd& joint, const Eigen::MatrixXd& fixed,
384 Eigen::Index anchor_rows, Eigen::Index query_rows, Eigen::Index dimensions,
385 const Eigen::VectorXd& anchor_noise, Eigen::MatrixXd& covariance,
386 const std::shared_ptr<linalg::DistributedState>& execution)
387{
388 if (!validOnAllRanks(fixed.size() == 0 || (fixed.rows() == joint.rows() &&
389 fixed.cols() == joint.cols()),
390 execution)) {
391 valid_ = false;
392 factor_.reset();
393 return false;
394 }
395 if (fixed.size() == 0)
396 return prepare(joint, anchor_rows, query_rows, dimensions, anchor_noise,
397 covariance, execution);
398 return prepareJoint(joint + fixed, anchor_rows, query_rows, dimensions,
399 anchor_noise, covariance, execution);
400}
401
403 const KernelOperator& kernel, const Coord& anchors, const Coord& query,
404 const Eigen::VectorXd& anchor_noise, Eigen::MatrixXd& covariance,
405 const std::shared_ptr<linalg::DistributedState>& execution)
406{
407 valid_ = false;
408 factor_.reset();
409 if (!validOnAllRanks(
410 anchors.rows() > 0 && query.rows() > 0 && anchors.cols() > 0 &&
411 anchors.cols() == query.cols() && anchors.allFinite() &&
412 query.allFinite() &&
413 anchor_noise.size() == anchors.rows() * (anchors.cols() + 1) &&
414 anchor_noise.allFinite() && (anchor_noise.array() >= 0.0).all(),
415 execution))
416 return false;
417 anchor_rows_ = anchors.rows();
418 query_rows_ = query.rows();
419 dimensions_ = anchors.cols();
420#ifdef GPR_LINALG_SCALAPACK
421 if (execution) {
422 // Whole observation tiles share kernel geometry and belong to their
423 // factor owners. No rank materializes the dense anchor covariance.
424 const Eigen::Index channels = dimensions_ + 1;
425 const Eigen::Index order = anchor_rows_ * channels;
426 if (order > std::numeric_limits<int>::max()) return false;
429 PhaseTimers::projection_max_anchor_rows, static_cast<long>(order));
430 execution->initialize(static_cast<int>(channels));
431 int descriptor[9];
432 auto local = execution->alloc_local(
433 static_cast<int>(order), static_cast<int>(order), descriptor);
434 if (local.empty()) local.resize(1, 0.0);
435 int valid = 1;
436 try {
438 "projection anchor assembly");
439 const auto prepared_tiles =
440 kernel.prepareJointCovarianceTiles(anchors);
441 const bool whole_tiles = execution->block_size() == channels;
442 for (Eigen::Index i = 0; i < anchor_rows_; ++i) {
443 for (Eigen::Index j = 0; j <= i; ++j) {
444 const int row_start = static_cast<int>(i * channels);
445 const int col_start = static_cast<int>(j * channels);
446 bool owned =
447 execution->owns_global_entry(row_start, col_start);
448 if (!whole_tiles && !owned)
449 for (Eigen::Index a = 0; a < channels && !owned; ++a)
450 for (Eigen::Index b = 0; b < channels; ++b)
451 if (execution->owns_global_entry(
452 row_start + a, col_start + b)) {
453 owned = true;
454 break;
455 }
456 if (!owned) continue;
457 const Eigen::MatrixXd tile =
458 prepared_tiles
459 ? prepared_tiles(i, j)
461 anchors.middleRows(i, 1),
462 anchors.middleRows(j, 1));
463 if (tile.rows() != channels || tile.cols() != channels ||
464 !tile.allFinite()) {
465 valid = 0;
466 continue;
467 }
468 if (whole_tiles) {
469 // An observation tile occupies one process block.
470 // Its columns are contiguous in the local matrix;
471 // ownership and local offsets are constant per tile.
472 const int local_row = execution->local_index_for_global(
473 row_start, execution->block_size(),
474 execution->myrow(), execution->nprow());
475 const int local_col = execution->local_index_for_global(
476 col_start, execution->block_size(),
477 execution->mycol(), execution->npcol());
478 for (Eigen::Index b = 0; b < channels; ++b) {
479 double* column =
480 local.data() + local_row +
481 static_cast<std::size_t>(local_col + b) *
482 descriptor[8];
483 for (Eigen::Index a = i == j ? b : 0; a < channels;
484 ++a)
485 column[a] =
486 tile(a, b) +
487 (i == j && a == b
488 ? anchor_noise(a * anchor_rows_ + i)
489 : 0.0);
490 }
491 continue;
492 }
493 for (Eigen::Index a = 0; a < channels; ++a)
494 for (Eigen::Index b = 0; b < channels; ++b) {
495 const int row = row_start + a, col = col_start + b;
496 if (row < col ||
497 !execution->owns_global_entry(row, col))
498 continue;
499 const int local_row =
500 execution->local_index_for_global(
501 row, execution->block_size(),
502 execution->myrow(), execution->nprow());
503 const int local_col =
504 execution->local_index_for_global(
505 col, execution->block_size(),
506 execution->mycol(), execution->npcol());
507 local[local_row +
508 static_cast<std::size_t>(local_col) *
509 descriptor[8]] =
510 tile(a, b) +
511 (row == col ? anchor_noise(a * anchor_rows_ + i)
512 : 0.0);
513 }
514 }
515 }
516 } catch (const std::exception&) {
517 valid = 0;
518 }
519 if (execution->nprocs() > 1)
520 MPI_Allreduce(MPI_IN_PLACE, &valid, 1, MPI_INT, MPI_MIN,
521 execution->world_comm());
522 if (!valid) return false;
523 factor_ = std::make_unique<Factor>();
524 factor_->observation_major = true;
525 factor_->distributed =
526 std::make_unique<linalg::ScalapackPDPotrfInverse>(execution);
527 {
529 "projection factor");
530 if (!factor_->distributed->factorise(std::move(local), descriptor,
531 static_cast<int>(order)))
532 return false;
533 }
534 Eigen::MatrixXd aq, qq;
535 try {
537 "projection cross covariance");
538 aq = kernel.jointEnergyGradientCrossCovariance(anchors, query);
539 qq = kernel.jointEnergyGradientCovariance(query);
540 const Eigen::Index query_order = query_rows_ * channels;
541 valid = aq.rows() == order && aq.cols() == query_order &&
542 qq.rows() == query_order && qq.cols() == query_order &&
543 aq.allFinite() && qq.allFinite();
544 } catch (const std::exception&) {
545 valid = 0;
546 }
547 if (execution->nprocs() > 1)
548 MPI_Allreduce(MPI_IN_PLACE, &valid, 1, MPI_INT, MPI_MIN,
549 execution->world_comm());
550 if (!valid) return false;
551 Eigen::MatrixXd ordered(aq.rows(), aq.cols());
552 for (Eigen::Index row = 0; row < order; ++row)
553 ordered.row(row) =
554 aq.row((row % channels) * anchor_rows_ + row / channels);
555 {
557 "projection solve");
558 ordered = factor_->distributed->solve_mat(ordered);
559 }
560 weights_.resize(aq.rows(), aq.cols());
561 for (Eigen::Index row = 0; row < order; ++row)
562 weights_.row((row % channels) * anchor_rows_ + row / channels) =
563 ordered.row(row);
564 {
566 "projection Schur complement");
567 covariance = conditionalCovariance(qq, aq, weights_);
568 }
569 valid_ = covariance.allFinite() && weights_.allFinite();
570 return valid_;
571 }
572#endif
573 return prepareBlocks(
574 kernel.jointEnergyGradientCovariance(anchors),
575 kernel.jointEnergyGradientCrossCovariance(anchors, query),
576 kernel.jointEnergyGradientCovariance(query), anchor_noise, covariance,
577 execution);
578}
579
580bool ConditionalKernelProjection::prepareBlocks(
581 Eigen::MatrixXd aa, const Eigen::MatrixXd& aq, const Eigen::MatrixXd& qq,
582 const Eigen::VectorXd& anchor_noise, Eigen::MatrixXd& covariance,
583 const std::shared_ptr<linalg::DistributedState>& execution)
584{
585 const Eigen::Index na = anchor_rows_ * (dimensions_ + 1);
586 const Eigen::Index nq = query_rows_ * (dimensions_ + 1);
587 bool anchor_shape_valid = aa.rows() == na && aa.cols() == na;
588#ifdef GPR_LINALG_SCALAPACK
589 if (execution) {
590 if (na > std::numeric_limits<int>::max()) return false;
591 execution->initialize();
592 anchor_shape_valid =
593 anchor_shape_valid || (!execution->is_root() && aa.size() == 0);
594 }
595#endif
596 if (!validOnAllRanks(anchor_shape_valid && aq.rows() == na &&
597 aq.cols() == nq && qq.rows() == nq &&
598 qq.cols() == nq && aa.allFinite() &&
599 aq.allFinite() && qq.allFinite(),
600 execution))
601 return false;
604 PhaseTimers::projection_max_anchor_rows, static_cast<long>(na));
605 factor_ = std::make_unique<Factor>();
606 if (aa.size()) aa.diagonal() += anchor_noise;
607#ifdef GPR_LINALG_SCALAPACK
608 if (execution) {
609 factor_->distributed =
610 std::make_unique<linalg::ScalapackPDPotrfInverse>(execution);
611 int descriptor[9];
612 auto values = execution->scatter(aa, static_cast<int>(na),
613 static_cast<int>(na), descriptor);
614 aa.resize(0, 0);
615 {
616 ScopedPhaseTimer timer(PhaseTimers::projection_factor_seconds,
617 "projection factor");
618 if (!factor_->distributed->factorise(std::move(values), descriptor,
619 static_cast<int>(na)))
620 return false;
621 }
622 {
623 ScopedPhaseTimer timer(PhaseTimers::projection_solve_seconds,
624 "projection solve");
625 weights_ = factor_->distributed->solve_mat(aq);
626 }
627 } else
628#else
629 if (execution)
630 throw std::invalid_argument(
631 "distributed kernel conditioning is unavailable");
632#endif
633 {
634 factor_->lower = std::move(aa);
636 {
637 ScopedPhaseTimer timer(PhaseTimers::projection_factor_seconds,
638 "projection factor");
639 if (!linalg::trainingCholeskyLower(factor_->lower))
640 return false;
641 }
642 ScopedPhaseTimer timer(PhaseTimers::projection_solve_seconds,
643 "projection solve");
644 weights_ = factor_->lower.triangularView<Eigen::Lower>().solve(aq);
645 factor_->lower.transpose()
646 .triangularView<Eigen::Upper>()
647 .solveInPlace(weights_);
648 } else {
649 const auto local = [&] {
650 ScopedPhaseTimer timer(PhaseTimers::projection_factor_seconds,
651 "projection factor");
652 return Eigen::LLT<Eigen::Ref<Eigen::MatrixXd>>(factor_->lower);
653 }();
654 if (local.info() != Eigen::Success) return false;
655 {
656 ScopedPhaseTimer timer(PhaseTimers::projection_solve_seconds,
657 "projection solve");
658 weights_ = local.solve(aq);
659 }
660 }
661 }
662 {
663 ScopedPhaseTimer timer(PhaseTimers::projection_schur_seconds,
664 "projection Schur complement");
665 covariance = conditionalCovariance(qq, aq, weights_);
666 }
667 valid_ = covariance.allFinite() && weights_.allFinite();
668 return valid_;
669}
670
671std::shared_ptr<const KernelOperator> ConditionalKernelProjection::intoKernel(
672 std::shared_ptr<const KernelOperator> kernel, Coord anchors) &&
673{
674 if (!valid_ || !factor_ || !kernel || anchors.rows() != anchor_rows_ ||
675 anchors.cols() != dimensions_ || !anchors.allFinite())
676 throw std::invalid_argument("invalid fitted kernel projection");
677 auto state = std::make_unique<ConditionedKernel::State>();
678 state->observation_major = factor_->observation_major;
679#ifdef GPR_LINALG_SCALAPACK
680 if (factor_->distributed)
681 state->lower = factor_->distributed->lowerFactorPanels();
682 else
683#endif
684 state->lower = linalg::CholeskyPanels::fromLower(factor_->lower);
685 state->kernel = std::move(kernel);
686 state->anchors = std::move(anchors);
687 state->anchor_covariance =
688 makeKernelCrossCovariance(state->kernel, state->anchors);
689 auto result = std::shared_ptr<const KernelOperator>(
690 new ConditionedKernel(std::move(state)));
691 factor_.reset();
692 weights_.resize(0, 0);
693 valid_ = false;
694 return result;
695}
696
697template <typename Derived>
698void ConditionalKernelProjection::blocks(
699 const Eigen::MatrixBase<Derived>& matrix, Eigen::MatrixXd& aa,
700 Eigen::MatrixXd& aq, Eigen::MatrixXd& qq, bool include_anchor) const
701{
702 const Eigen::Index rows = anchor_rows_ + query_rows_;
703 const Eigen::Index na = anchor_rows_ * (dimensions_ + 1);
704 const Eigen::Index nq = query_rows_ * (dimensions_ + 1);
705 if (include_anchor)
706 aa.resize(na, na);
707 else
708 aa.resize(0, 0);
709 aq.resize(na, nq);
710 qq.resize(nq, nq);
711 for (Eigen::Index a = 0; a <= dimensions_; ++a)
712 for (Eigen::Index b = 0; b <= dimensions_; ++b) {
713 if (include_anchor)
714 aa.block(a * anchor_rows_, b * anchor_rows_, anchor_rows_,
715 anchor_rows_) =
716 matrix.block(a * rows, b * rows, anchor_rows_,
717 anchor_rows_);
718 aq.block(a * anchor_rows_, b * query_rows_, anchor_rows_,
719 query_rows_) =
720 matrix.block(a * rows, b * rows + anchor_rows_, anchor_rows_,
721 query_rows_);
722 qq.block(a * query_rows_, b * query_rows_, query_rows_,
723 query_rows_) =
724 matrix.block(a * rows + anchor_rows_, b * rows + anchor_rows_,
725 query_rows_, query_rows_);
726 }
727}
728
730 const Eigen::MatrixXd& matrix) const
731{
732 const Eigen::Index channels =
733 (anchor_rows_ + query_rows_) * (dimensions_ + 1);
734 if (!valid_ || matrix.rows() != channels || matrix.cols() != channels ||
735 !matrix.allFinite())
736 throw std::invalid_argument("invalid conditioned kernel derivative");
737 Eigen::MatrixXd aa, aq, qq;
738 blocks(matrix, aa, aq, qq);
739 const Eigen::MatrixXd cross = aq.transpose() * weights_;
740 return symmetric(qq - cross - cross.transpose() +
741 weights_.transpose() * aa * weights_);
742}
743
745 const Eigen::MatrixXd& conditional_weight) const
746{
747 const Eigen::Index nq = query_rows_ * (dimensions_ + 1);
748 if (!valid_ || conditional_weight.rows() != nq ||
749 conditional_weight.cols() != nq || !conditional_weight.allFinite())
750 throw std::invalid_argument("invalid conditioned kernel weight");
751 const Eigen::MatrixXd qq = symmetric(conditional_weight);
752 const Eigen::MatrixXd aq = -weights_ * qq;
753 const Eigen::Index rows = anchor_rows_ + query_rows_;
754 const Eigen::Index channels = rows * (dimensions_ + 1);
755 Eigen::MatrixXd result(channels, channels);
756 for (Eigen::Index a = 0; a <= dimensions_; ++a) {
757 // A channel of anchor rows bounds the product workspace without
758 // retaining another full anchor matrix beside the joint adjoint.
759 const Eigen::MatrixXd aa_rows =
760 -aq.middleRows(a * anchor_rows_, anchor_rows_) *
761 weights_.transpose();
762 for (Eigen::Index b = 0; b <= dimensions_; ++b) {
763 result.block(a * rows, b * rows, anchor_rows_, anchor_rows_) =
764 aa_rows.middleCols(b * anchor_rows_, anchor_rows_);
765 result.block(a * rows, b * rows + anchor_rows_, anchor_rows_,
766 query_rows_) =
767 aq.block(a * anchor_rows_, b * query_rows_, anchor_rows_,
768 query_rows_);
769 result.block(a * rows + anchor_rows_, b * rows, query_rows_,
770 anchor_rows_) =
771 aq.block(b * anchor_rows_, a * query_rows_, anchor_rows_,
772 query_rows_)
773 .transpose();
774 result.block(a * rows + anchor_rows_, b * rows + anchor_rows_,
775 query_rows_, query_rows_) =
776 qq.block(a * query_rows_, b * query_rows_, query_rows_,
777 query_rows_);
778 }
779 }
780 for (Eigen::Index j = 0; j < channels; ++j)
781 for (Eigen::Index i = j + 1; i < channels; ++i) {
782 const double value = 0.5 * (result(i, j) + result(j, i));
783 result(i, j) = value;
784 result(j, i) = value;
785 }
786 return result;
787}
788
790 Eigen::Index first, Eigen::Index count) const
791{
792 const Eigen::Index rows = anchor_rows_ + query_rows_;
793 const Eigen::Index nq = query_rows_ * (dimensions_ + 1);
794 if (!valid_ || first < 0 || count < 0 || first > rows ||
795 count > rows - first)
796 throw std::invalid_argument(
797 "invalid conditioned observation lift rows");
798 Eigen::MatrixXd lift = Eigen::MatrixXd::Zero(count * (dimensions_ + 1), nq);
799 const Eigen::Index anchor_count =
800 first < anchor_rows_ ? std::min(count, anchor_rows_ - first) : 0;
801 const Eigen::Index query_count = count - anchor_count;
802 const Eigen::Index query_first = first + anchor_count - anchor_rows_;
803 for (Eigen::Index channel = 0; channel <= dimensions_; ++channel) {
804 if (anchor_count)
805 lift.middleRows(channel * count, anchor_count) =
806 -weights_.middleRows(channel * anchor_rows_ + first,
807 anchor_count);
808 for (Eigen::Index row = 0; row < query_count; ++row)
809 lift(channel * count + anchor_count + row,
810 channel * query_rows_ + query_first + row) = 1.0;
811 }
812 return lift;
813}
814
816 const Eigen::MatrixXd& conditional_weight, Eigen::Index first,
817 Eigen::Index count) const
818{
819 const Eigen::Index rows = anchor_rows_ + query_rows_;
820 const Eigen::Index nq = query_rows_ * (dimensions_ + 1);
821 if (!valid_ || first < 0 || count < 0 || first > rows ||
822 count > rows - first || conditional_weight.rows() != nq ||
823 conditional_weight.cols() != nq || !conditional_weight.allFinite())
824 throw std::invalid_argument("invalid conditioned kernel weight rows");
825 const Eigen::MatrixXd qq = symmetric(conditional_weight);
826 const Eigen::Index local_rows = count * (dimensions_ + 1);
827 Eigen::MatrixXd query_weight(local_rows, nq);
828 const Eigen::Index anchor_count =
829 first < anchor_rows_ ? std::min(count, anchor_rows_ - first) : 0;
830 const Eigen::Index query_count = count - anchor_count;
831 const Eigen::Index query_first = first + anchor_count - anchor_rows_;
832 for (Eigen::Index a = 0; a <= dimensions_; ++a) {
833 if (anchor_count)
834 query_weight.middleRows(a * count, anchor_count).noalias() =
835 -weights_.middleRows(a * anchor_rows_ + first, anchor_count) *
836 qq;
837 if (query_count)
838 query_weight.middleRows(a * count + anchor_count, query_count) =
839 qq.middleRows(a * query_rows_ + query_first, query_count);
840 }
841 Eigen::MatrixXd result(local_rows, rows * (dimensions_ + 1));
842 for (Eigen::Index b = 0; b <= dimensions_; ++b) {
843 result.middleCols(b * rows, anchor_rows_).noalias() =
844 -query_weight *
845 weights_.middleRows(b * anchor_rows_, anchor_rows_).transpose();
846 result.middleCols(b * rows + anchor_rows_, query_rows_) =
847 query_weight.middleCols(b * query_rows_, query_rows_);
848 }
849 return result;
850}
851
853 const Eigen::MatrixXd& joint,
854 const std::vector<Eigen::MatrixXd>& derivatives, Eigen::Index anchor_rows,
855 Eigen::Index query_rows, Eigen::Index dimensions,
856 const Eigen::VectorXd& anchor_noise, Eigen::MatrixXd& covariance,
857 std::vector<Eigen::MatrixXd>& conditional_derivatives,
858 const linalg::LocalExecutor& execution)
859{
861 if (!projection.prepare(joint, anchor_rows, query_rows, dimensions,
862 anchor_noise, covariance))
863 return false;
864 conditional_derivatives.clear();
865 for (const auto& derivative: derivatives)
866 if (derivative.rows() != joint.rows() ||
867 derivative.cols() != joint.cols() || !derivative.allFinite())
868 return false;
869 conditional_derivatives.resize(derivatives.size());
870 execution.forEach(derivatives.size(), [&](std::size_t index) {
871 conditional_derivatives[index] =
872 projection.derivative(derivatives[index]);
873 });
874 return true;
875}
876
877} // namespace gpr
Distributed ScaLAPACK pdpotrf-based KernelInverse impl.
#define GPR_LINALG_SCALAPACK
Definition SlateBackend.h:9
Eigen::MatrixXd adjoint(const Eigen::MatrixXd &conditional_weight) const
Eigen::MatrixXd derivative(const Eigen::MatrixXd &matrix) const
Eigen::MatrixXd adjointRows(const Eigen::MatrixXd &conditional_weight, Eigen::Index first, Eigen::Index count) const
Eigen::MatrixXd observationLiftRows(Eigen::Index first, Eigen::Index count) const
bool prepare(const Eigen::MatrixXd &joint, Eigen::Index anchor_rows, Eigen::Index query_rows, Eigen::Index dimensions, const Eigen::VectorXd &anchor_noise, Eigen::MatrixXd &covariance, const std::shared_ptr< linalg::DistributedState > &execution={})
std::shared_ptr< const KernelOperator > intoKernel(std::shared_ptr< const KernelOperator > kernel, Coord anchors) &&
Eigen::VectorXd applyJointCrossCovariance(const Eigen::MatrixXd &left, const Eigen::MatrixXd &right, const Eigen::VectorXd &weights) const override
ConditionedKernel(std::shared_ptr< const KernelOperator > kernel, Coord anchors, Eigen::VectorXd noise)
Eigen::MatrixXd jointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left, const Eigen::MatrixXd &right) const override
Cross covariance in Observation order on each operand.
MeanHessianFunction prepareMeanHessianVector(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
CrossCovarianceFunction prepareCrossCovariance(const Eigen::MatrixXd &training) const override
~ConditionedKernel() override
Eigen::MatrixXd jointEnergyGradientCovariance(const Eigen::MatrixXd &positions) const override
Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
MeanHessianPreparation prepareMeanHessian(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
MeanCurvature meanCurvature() const noexcept override
bool meanHessianVector(const Coord &training, const Eigen::VectorXd &weights, const Eigen::VectorXd &position, const Eigen::VectorXd &direction, Eigen::VectorXd &action) const override
MeanFunction prepareMean(const Eigen::MatrixXd &training, const Eigen::VectorXd &weights) const override
Eigen::VectorXd jointEnergyGradientDiagonal(const Eigen::MatrixXd &positions) const override
Marginal prior variances in the same channel order as the joint matrix.
Eigen::MatrixXd covarianceBlock(const Eigen::MatrixXd &left, const Eigen::MatrixXd &right, Eigen::Index left_channel, Eigen::Index right_channel) const override
Covariance between one channel at each set of geometry rows.
virtual JointCovarianceTileFunction prepareJointCovarianceTiles(const Eigen::MatrixXd &) const
std::function< HessianAction(const Eigen::VectorXd &)> MeanHessianPreparation
std::function< bool( const Eigen::VectorXd &, const Eigen::VectorXd &, Eigen::VectorXd &)> MeanHessianFunction
virtual Eigen::MatrixXd jointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions) const
Cross covariance in Observation order on each operand.
virtual Eigen::MatrixXd jointEnergyGradientCovariance(const Eigen::MatrixXd &positions) const
Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
std::function< Eigen::VectorXd(const Eigen::MatrixXd &)> MeanFunction
std::function< Eigen::MatrixXd(const Eigen::MatrixXd &)> CrossCovarianceFunction
static CholeskyPanels fromLower(const Eigen::MatrixXd &lower)
void forEach(std::size_t count, Operation &&operation, Grain grain=Grain::Fine) const
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
bool trainingCholeskyLower(ProductMatrix lower)
bool trainingCholeskySelected(Eigen::Index order)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
KernelOperator::CrossCovarianceFunction makeKernelCrossCovariance(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training)
bool conditionKernelMatrix(const Eigen::MatrixXd &joint, const std::vector< Eigen::MatrixXd > &derivatives, Eigen::Index anchor_rows, Eigen::Index query_rows, Eigen::Index dimensions, const Eigen::VectorXd &anchor_noise, Eigen::MatrixXd &covariance, std::vector< Eigen::MatrixXd > &conditional_derivatives)
FieldMatrixd Coord
Definition Macros.h:35
KernelOperator::MeanHessianFunction makeAnalyticKernelMeanHessianVector(const std::shared_ptr< const KernelOperator > &kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
KernelOperator::MeanFunction makeKernelMean(std::shared_ptr< const KernelOperator > kernel, const Eigen::MatrixXd &training, const Eigen::VectorXd &weights)
Owning fitted mean, using the kernel's representation or its exact product.
STL namespace.
Eigen::Matrix< double, Eigen::Dynamic, Derived::ColsAtCompileTime > solve(const Eigen::MatrixBase< Derived > &right) const
CrossCovarianceFunction anchor_covariance
Eigen::Matrix< double, Eigen::Dynamic, Derived::ColsAtCompileTime > whiten(const Eigen::MatrixBase< Derived > &right) const
Eigen::Matrix< double, Eigen::Dynamic, Derived::ColsAtCompileTime > factorRows(const Eigen::MatrixBase< Derived > &right) const
std::shared_ptr< const KernelOperator > kernel
static double projection_cross_seconds
static double projection_schur_seconds
static long projection_max_anchor_rows
static int projection_count
static double projection_factor_seconds
static double projection_assembly_seconds
static double projection_solve_seconds