Loading...
Searching...
No Matches
KokkosBackend.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3
4#include "KokkosBackend.h"
5
6#include <Eigen/Cholesky>
7#include <KokkosBlas3_gemm.hpp>
8#include <KokkosBlas3_trsm.hpp>
9#include <Kokkos_Core.hpp>
10#include <atomic>
11#include <cmath>
12#include <cstddef>
13#include <cstdlib>
14#include <cstring>
15#include <memory>
16#include <mutex>
17#include <stdexcept>
18#include <string>
19#include <type_traits>
20#include <utility>
21
23#include "ExactSchur.h"
24#include "KokkosAuditedCopy.h"
25#include "KokkosDeviceOps.h"
26#include "KokkosFactor.h"
27#include "LinalgThreads.h"
28#include "TeamFactor.h"
29#include "TrainingCholesky.h"
30
31namespace gpr {
32namespace linalg {
33namespace {
34struct GlobalKokkosTransferAudit {
35 std::atomic<std::size_t> h2d_calls{0}, h2d_bytes{0}, d2h_calls{0},
36 d2h_bytes{0}, d2d_calls{0}, d2d_bytes{0}, h2h_calls{0}, h2h_bytes{0},
37 to_exec_calls{0}, to_exec_bytes{0}, to_host_calls{0}, to_host_bytes{0},
38 mirror_calls{0}, mirror_bytes{0}, max_to_exec{0}, max_to_host{0};
39};
40GlobalKokkosTransferAudit& transfer_audit()
41{
42 static GlobalKokkosTransferAudit counters;
43 return counters;
44}
45void add_pair(std::atomic<std::size_t>& calls, std::atomic<std::size_t>& bytes,
46 std::size_t amount) noexcept
47{
48 calls.fetch_add(1, std::memory_order_relaxed);
49 bytes.fetch_add(amount, std::memory_order_relaxed);
50}
51void raise_max(std::atomic<std::size_t>& slot, std::size_t bytes) noexcept
52{
53 std::size_t seen = slot.load(std::memory_order_relaxed);
54 while (bytes > seen &&
55 !slot.compare_exchange_weak(seen, bytes, std::memory_order_relaxed))
56 ;
57}
58} // namespace
59
61{
62 auto& audit = transfer_audit();
63 audit.h2d_calls.store(0, std::memory_order_relaxed);
64 audit.h2d_bytes.store(0, std::memory_order_relaxed);
65 audit.d2h_calls.store(0, std::memory_order_relaxed);
66 audit.d2h_bytes.store(0, std::memory_order_relaxed);
67 audit.d2d_calls.store(0, std::memory_order_relaxed);
68 audit.d2d_bytes.store(0, std::memory_order_relaxed);
69 audit.h2h_calls.store(0, std::memory_order_relaxed);
70 audit.h2h_bytes.store(0, std::memory_order_relaxed);
71 audit.to_exec_calls.store(0, std::memory_order_relaxed);
72 audit.to_exec_bytes.store(0, std::memory_order_relaxed);
73 audit.to_host_calls.store(0, std::memory_order_relaxed);
74 audit.to_host_bytes.store(0, std::memory_order_relaxed);
75 audit.mirror_calls.store(0, std::memory_order_relaxed);
76 audit.mirror_bytes.store(0, std::memory_order_relaxed);
77 audit.max_to_exec.store(0, std::memory_order_relaxed);
78 audit.max_to_host.store(0, std::memory_order_relaxed);
79}
80
82{
83 auto& audit = transfer_audit();
85 result.host_to_device.calls =
86 audit.h2d_calls.load(std::memory_order_relaxed);
87 result.host_to_device.bytes =
88 audit.h2d_bytes.load(std::memory_order_relaxed);
89 result.device_to_host.calls =
90 audit.d2h_calls.load(std::memory_order_relaxed);
91 result.device_to_host.bytes =
92 audit.d2h_bytes.load(std::memory_order_relaxed);
93 result.device_to_device.calls =
94 audit.d2d_calls.load(std::memory_order_relaxed);
95 result.device_to_device.bytes =
96 audit.d2d_bytes.load(std::memory_order_relaxed);
97 result.host_to_host.calls = audit.h2h_calls.load(std::memory_order_relaxed);
98 result.host_to_host.bytes = audit.h2h_bytes.load(std::memory_order_relaxed);
100 audit.to_exec_calls.load(std::memory_order_relaxed);
102 audit.to_exec_bytes.load(std::memory_order_relaxed);
103 result.boundary_to_host.calls =
104 audit.to_host_calls.load(std::memory_order_relaxed);
105 result.boundary_to_host.bytes =
106 audit.to_host_bytes.load(std::memory_order_relaxed);
107 result.mirror_create_calls =
108 audit.mirror_calls.load(std::memory_order_relaxed);
109 result.mirror_create_bytes =
110 audit.mirror_bytes.load(std::memory_order_relaxed);
112 audit.max_to_exec.load(std::memory_order_relaxed);
113 result.max_boundary_to_host =
114 audit.max_to_host.load(std::memory_order_relaxed);
115 return result;
116}
117
118void detail::recordKokkosDeepCopy(bool source_host, bool destination_host,
119 std::size_t bytes) noexcept
120{
121 auto& audit = transfer_audit();
122 if (source_host && !destination_host)
123 add_pair(audit.h2d_calls, audit.h2d_bytes, bytes);
124 else if (!source_host && destination_host)
125 add_pair(audit.d2h_calls, audit.d2h_bytes, bytes);
126 else if (!source_host && !destination_host)
127 add_pair(audit.d2d_calls, audit.d2d_bytes, bytes);
128 else
129 add_pair(audit.h2h_calls, audit.h2h_bytes, bytes);
130}
131
132void detail::recordKokkosMirrorCreate(std::size_t bytes) noexcept
133{
134 add_pair(transfer_audit().mirror_calls, transfer_audit().mirror_bytes,
135 bytes);
136}
137
138void detail::recordKokkosBoundaryToExecution(std::size_t bytes) noexcept
139{
140 auto& audit = transfer_audit();
141 add_pair(audit.to_exec_calls, audit.to_exec_bytes, bytes);
142 raise_max(audit.max_to_exec, bytes);
143}
144
145void detail::recordKokkosBoundaryToHost(std::size_t bytes) noexcept
146{
147 auto& audit = transfer_audit();
148 add_pair(audit.to_host_calls, audit.to_host_bytes, bytes);
149 raise_max(audit.max_to_host, bytes);
150}
151
152namespace {
153thread_local detail::KokkosCopyContext copy_context =
154 detail::KokkosCopyContext::Unaudited;
155} // namespace
156
157detail::KokkosCopyContext detail::kokkosCopyContext() noexcept
158{
159 return copy_context;
160}
161
162detail::KokkosCopyScope::KokkosCopyScope(KokkosCopyContext context) noexcept
163 : previous_(copy_context)
164{
165 copy_context = context;
166}
167
168detail::KokkosCopyScope::~KokkosCopyScope()
169{
170 copy_context = previous_;
171}
172
174{
175 return std::is_same_v<Kokkos::DefaultExecutionSpace::memory_space,
176 Kokkos::HostSpace>;
177}
178
179namespace {
180
181void requireKokkosRuntime()
182{
183 // A host Eigen factor does not touch a Kokkos view, so a process that
184 // never started the runtime, and one that already finalized it, would
185 // otherwise keep factoring. ensure_kokkos() starts the runtime on first
186 // use and throws std::logic_error once it has been finalized, the same
187 // contract as a view allocation.
188 detail::ensure_kokkos();
189}
190
191// Device memory: the factor and the solves run in execution memory, and the
192// Eigen result is downloaded once at the end.
193bool deviceCholesky(const EigenMatrix& C,
194 const CovarianceEquilibration& scaling, EigenMatrix& L)
195{
196 KernelWall wall(KernelWall::Kind::Factor);
197 const int n =
198 detail::kokkosSolverExtent(static_cast<std::size_t>(C.rows()));
199
200 EigenMatrix scaled = C;
201 scaling.scaleLower(scaled);
202 auto d_L = detail::to_device(detail::wrap(scaled), "chol_L");
203
204 if (!detail::kokkosFactorLower(detail::exec_space{}, d_L)) return false;
205 EigenMatrix factor;
206 detail::to_eigen(d_L, factor);
207 scaling.restoreFactor(factor);
208
209 // Zero upper triangle (potrf leaves original values there)
210 for (int j = 1; j < n; ++j)
211 for (int i = 0; i < j; ++i)
212 factor(i, j) = 0.0;
213 if (!factor.allFinite()) return false;
214 L = std::move(factor);
215 return true;
216}
217
218EigenMatrix deviceTriangularSolve(const EigenMatrix& L, const EigenMatrix& B,
219 bool transpose)
220{
221 KernelWall wall(KernelWall::Kind::Solve);
222 auto d_L = detail::to_device(detail::wrap(L), "trsm_L");
223 auto d_X = detail::to_device(detail::wrap(B), "trsm_X");
224 detail::solve_lower(detail::exec_space{}, d_L, d_X, transpose);
225 EigenMatrix X;
226 detail::to_eigen(d_X, X);
227 return X;
228}
229
230EigenMatrix deviceCholeskyInverse(const EigenMatrix& L)
231{
232 KernelWall wall(KernelWall::Kind::Solve);
233 const int n =
234 detail::kokkosSolverExtent(static_cast<std::size_t>(L.rows()));
235 auto d_L = detail::to_device(detail::wrap(L), "chinv_L");
236 detail::device_matrix_t d_I("I", n, n);
237 detail::device_matrix_t d_invC("invC", n, n);
238 detail::cholesky_inverse_on_device(d_L, d_I, d_invC);
239 EigenMatrix invC;
240 detail::to_eigen(d_invC, invC);
241 return invC;
242}
243
244} // namespace
245
246bool cholesky(const EigenMatrix& C, EigenMatrix& L)
247{
248 if (C.rows() != C.cols()) return false;
249 requireKokkosRuntime();
250 detail::kokkosSolverExtent(static_cast<std::size_t>(C.rows()));
251 CovarianceEquilibration scaling;
252 if (!scaling.compute(C.diagonal())) return false;
253 if (!kokkosHostExecutionMemory()) return deviceCholesky(C, scaling, L);
254 // Host execution memory: the matrix is already where the factor runs,
255 // so the Eigen backend's equilibrated factor runs in place.
256 KernelWall wall(KernelWall::Kind::Factor);
257 if (trainingCholeskySelected(C.rows())) {
258 EigenMatrix lower = EigenMatrix::NullaryExpr(
259 C.rows(), C.cols(), [&](Eigen::Index i, Eigen::Index j) {
260 return i >= j ? scaling.covariance(C(i, j), i, j) : 0.0;
261 });
262 if (!trainingCholeskyLower(lower)) return false;
263 scaling.restoreFactor(lower);
264 L = std::move(lower);
265 return true;
266 }
267#if defined(USE_OPENMP)
268 if (teamPanelKernels()) {
269 EigenMatrix lower = EigenMatrix::NullaryExpr(
270 C.rows(), C.cols(), [&](Eigen::Index i, Eigen::Index j) {
271 return i >= j ? scaling.covariance(C(i, j), i, j) : 0.0;
272 });
273 if (!teamCholeskyLower(lower)) return false;
274 scaling.restoreFactor(lower);
275 L = std::move(lower);
276 return true;
277 }
278#endif
279 Eigen::LLT<EigenMatrix> llt;
280 llt.compute(EigenMatrix::NullaryExpr(
281 C.rows(), C.cols(), [&](Eigen::Index i, Eigen::Index j) {
282 return i >= j ? scaling.covariance(C(i, j), i, j) : 0.0;
283 }));
284 if (llt.info() != Eigen::Success) return false;
285 L = llt.matrixL();
286 scaling.restoreFactor(L);
287 return L.allFinite();
288}
289
291{
292 if (L.rows() != L.cols() || B.rows() != L.rows())
293 throw std::invalid_argument(
294 "Kokkos triangular solve has incompatible shapes");
295 if (L.rows() == 0 || B.cols() == 0) return EigenMatrix(L.rows(), B.cols());
296 requireKokkosRuntime();
297 if (!kokkosHostExecutionMemory()) return deviceTriangularSolve(L, B, false);
298#if defined(USE_OPENMP)
299 if (teamPanelKernels()) {
300 EigenMatrix X = B;
301 teamSolveLower(L, true, X);
302 return X;
303 }
304#endif
305 KernelWall wall(KernelWall::Kind::Solve);
306 return L.template triangularView<Eigen::Lower>().solve(B);
307}
308
310{
311 if (L.rows() != L.cols() || B.rows() != L.rows())
312 throw std::invalid_argument(
313 "Kokkos triangular solve has incompatible shapes");
314 if (L.rows() == 0 || B.cols() == 0) return EigenMatrix(L.rows(), B.cols());
315 requireKokkosRuntime();
316 if (!kokkosHostExecutionMemory()) return deviceTriangularSolve(L, B, true);
317#if defined(USE_OPENMP)
318 if (teamPanelKernels()) {
319 EigenMatrix X = B;
320 teamSolveLower(L, false, X);
321 return X;
322 }
323#endif
324 KernelWall wall(KernelWall::Kind::Solve);
325 return L.transpose().template triangularView<Eigen::Upper>().solve(B);
326}
327
328// On host execution memory a vector takes the matrix-vector sweep, as the
329// Eigen backend does, so a vector solve has the Eigen backend's bits.
330Eigen::VectorXd forward_solve(const EigenMatrix& L, const Eigen::VectorXd& b)
331{
332 if (L.rows() != L.cols() || b.size() != L.rows())
333 throw std::invalid_argument(
334 "Kokkos triangular solve has incompatible shapes");
335 requireKokkosRuntime();
336 if (!kokkosHostExecutionMemory() || L.rows() == 0) {
337 const EigenMatrix rhs = b;
338 return forward_solve_mat(L, rhs).col(0);
339 }
340#if defined(USE_OPENMP)
341 if (teamPanelKernels()) {
342 Eigen::VectorXd x = b;
343 teamSolveLowerVector(L, true, x);
344 return x;
345 }
346#endif
347 KernelWall wall(KernelWall::Kind::Solve);
348 return L.template triangularView<Eigen::Lower>().solve(b);
349}
350
351Eigen::VectorXd back_solve(const EigenMatrix& L, const Eigen::VectorXd& b)
352{
353 if (L.rows() != L.cols() || b.size() != L.rows())
354 throw std::invalid_argument(
355 "Kokkos triangular solve has incompatible shapes");
356 requireKokkosRuntime();
357 if (!kokkosHostExecutionMemory() || L.rows() == 0) {
358 const EigenMatrix rhs = b;
359 return back_solve_mat(L, rhs).col(0);
360 }
361#if defined(USE_OPENMP)
362 if (teamPanelKernels()) {
363 Eigen::VectorXd x = b;
364 teamSolveLowerVector(L, false, x);
365 return x;
366 }
367#endif
368 KernelWall wall(KernelWall::Kind::Solve);
369 return L.transpose().template triangularView<Eigen::Upper>().solve(b);
370}
371
373 const EigenMatrix& B)
374{
375 const EigenMatrix X = forward_solve_mat(L, B);
376 return X.colwise().squaredNorm().transpose();
377}
378
379Eigen::VectorXd bordered_cholesky_diagonal(const EigenMatrix& L,
380 const EigenMatrix& B,
381 const Eigen::VectorXd& prior)
382{
383 return borderedCholeskyDiagonal(prior, forward_solve_mat(L, B), L);
384}
385
387{
388 if (L.rows() != L.cols())
389 throw std::invalid_argument("Kokkos inverse requires a square factor");
390 if (L.rows() == 0) return EigenMatrix(0, 0);
391 requireKokkosRuntime();
392 if (!kokkosHostExecutionMemory()) return deviceCholeskyInverse(L);
393 detail::kokkosSolverExtent(static_cast<std::size_t>(L.rows()));
394 EigenMatrix L_inv;
395#if defined(USE_OPENMP)
396 if (teamPanelKernels()) {
397 L_inv = EigenMatrix::Identity(L.rows(), L.cols());
398 teamSolveLower(L, true, L_inv);
399 EigenMatrix invC(L.rows(), L.cols());
400 teamSymmetricGram(L_inv.data(), L_inv.outerStride(), invC.data(),
401 invC.outerStride(), L_inv.rows());
402 return invC;
403 }
404#endif
405 KernelWall wall(KernelWall::Kind::Solve);
406 L_inv = L.template triangularView<Eigen::Lower>().solve(
407 EigenMatrix::Identity(L.rows(), L.cols()));
408 return L_inv.transpose() * L_inv;
409}
410
411double trace_product(const EigenMatrix& A, const EigenMatrix& B)
412{
413 if (A.rows() != B.rows() || A.cols() != B.cols())
414 throw std::invalid_argument(
415 "Kokkos trace product has incompatible shapes");
416 // Both operands are host results; a linear reduction needs no device copy.
417 return (A.cwiseProduct(B)).sum();
418}
419
420double log_det_cholesky(const EigenMatrix& L)
421{
422 // The physical host factor supplies its diagonal without a matrix transfer.
423 return L.diagonal().array().log().sum();
424}
425
426// Lifetime: the Impl is shared between the workspace and a Kokkos finalize
427// hook that holds only a weak reference. Kokkos runs finalize hooks before it
428// tears down its execution and memory spaces, so the hook releases every
429// retained View while deallocation is still valid and marks the Impl
430// finalized. Kokkos offers no hook removal, so each workspace that touched the
431// device leaves one small hook behind; the Impl is allocated separately from
432// its control block so that the leftover weak reference does not pin it.
434 std::mutex mutex;
435 std::weak_ptr<Impl> self;
436 bool hook_registered = false;
437 bool finalized = false;
438
440 bool resident = false;
441 detail::device_matrix_t factor;
442 detail::device_matrix_t work;
443 detail::device_matrix_t product;
444 detail::device_vector_t norms;
446
447 void release()
448 {
449 resident = false;
450 witness.resize(0, 0);
451 factor = detail::device_matrix_t();
452 work = detail::device_matrix_t();
453 product = detail::device_matrix_t();
454 norms = detail::device_vector_t();
455 }
456
457 void rejectFinalized() const
458 {
459 if (finalized || Kokkos::is_finalized())
460 throw std::logic_error("cannot use a finalized Kokkos runtime");
461 }
462
464 {
465 detail::ensure_kokkos();
466 if (hook_registered) return;
467 // Kokkos keeps its finalize hooks in an unsynchronized container.
468 static std::mutex hook_mutex;
469 std::lock_guard<std::mutex> lock(hook_mutex);
470 Kokkos::push_finalize_hook([weak = self]() {
471 if (const std::shared_ptr<Impl> owner = weak.lock()) {
472 std::lock_guard<std::mutex> guard(owner->mutex);
473 owner->finalized = true;
474 owner->release();
475 }
476 });
477 hook_registered = true;
478 }
479
480 void bindFactor(const EigenMatrix& supplied)
481 {
482 if (resident && detail::same_entries(supplied, witness)) return;
483 resident = false;
484 witness = supplied;
485 const auto n = static_cast<std::size_t>(witness.rows());
486 detail::reserve_view(factor, n, n, "gpr workspace factor");
487 detail::audited_deep_copy(factor, detail::wrap(witness),
488 detail::byte_count(witness.size()),
489 detail::CopyRole::ToExecution);
490 ++stats.factor_uploads;
491 stats.factor_upload_bytes += detail::byte_count(witness.size());
492 resident = true;
493 }
494
495 void uploadRhs(const EigenMatrix& rhs)
496 {
497 detail::reserve_view(work, static_cast<std::size_t>(rhs.rows()),
498 static_cast<std::size_t>(rhs.cols()),
499 "gpr workspace rhs");
500 detail::audited_deep_copy(work, detail::wrap(rhs),
501 detail::byte_count(rhs.size()),
502 detail::CopyRole::ToExecution);
503 stats.rhs_upload_bytes += detail::byte_count(rhs.size());
504 }
505
506 EigenMatrix download(const detail::device_matrix_t& source)
507 {
508 EigenMatrix result;
509 detail::to_eigen(source, result);
510 stats.result_download_bytes += detail::byte_count(result.size());
511 return result;
512 }
513
514 // Returns false when the request is empty and needs no device work.
515 bool checkSolve(const EigenMatrix& L, const EigenMatrix& B) const
516 {
517 if (L.rows() != L.cols() || B.rows() != L.rows())
518 throw std::invalid_argument(
519 "Kokkos triangular solve has incompatible shapes");
520 detail::kokkosSolverExtent(static_cast<std::size_t>(L.rows()));
521 detail::kokkosSolverExtent(static_cast<std::size_t>(B.cols()));
523 return L.rows() != 0 && B.cols() != 0;
524 }
525
526 void beginSolve(const EigenMatrix& L, const EigenMatrix& B)
527 {
529 bindFactor(L);
530 uploadRhs(B);
531 }
532
533 bool checkBoundSolve(const EigenMatrix& B) const
534 {
536 if (B.rows() != static_cast<Eigen::Index>(factor.extent(0)))
537 throw std::invalid_argument(
538 "Kokkos factor solve has incompatible shapes");
539 detail::kokkosSolverExtent(static_cast<std::size_t>(B.cols()));
540 return B.rows() != 0 && B.cols() != 0;
541 }
542};
543
544KokkosWorkspace::Impl& KokkosWorkspace::ensureState() const
545{
546 // Two threads may make the first call on one workspace together.
547 std::call_once(impl_once_, [this] {
548 // Separate control block: a leftover finalize-hook weak_ptr must not
549 // keep the Impl alive (see the lifetime note above).
550 impl_.reset(new Impl);
551 impl_->self = impl_;
552 });
553 return *impl_;
554}
555
557{
558 ensureState();
559 std::lock_guard<std::mutex> lock(impl_->mutex);
560 if (!impl_->checkSolve(L, B)) return EigenMatrix(L.rows(), B.cols());
562 impl_->beginSolve(L, B);
563 detail::solve_lower(detail::exec_space{}, impl_->factor, impl_->work,
564 false);
565 return impl_->download(impl_->work);
566}
567
569 const EigenMatrix& B)
570{
571 ensureState();
572 std::lock_guard<std::mutex> lock(impl_->mutex);
573 if (!impl_->checkSolve(L, B)) return EigenMatrix(L.rows(), B.cols());
575 impl_->beginSolve(L, B);
576 detail::solve_lower(detail::exec_space{}, impl_->factor, impl_->work, true);
577 return impl_->download(impl_->work);
578}
579
581{
582 ensureState();
583 std::lock_guard<std::mutex> lock(impl_->mutex);
584 if (!impl_->checkSolve(L, B)) return EigenMatrix(L.rows(), B.cols());
586 impl_->beginSolve(L, B);
587 detail::solve_lower(detail::exec_space{}, impl_->factor, impl_->work,
588 false);
589 detail::solve_lower(detail::exec_space{}, impl_->factor, impl_->work, true);
590 return impl_->download(impl_->work);
591}
592
594 const EigenMatrix& B)
595{
596 ensureState();
597 std::lock_guard<std::mutex> lock(impl_->mutex);
598 if (!impl_->checkSolve(L, B)) return Eigen::VectorXd::Zero(B.cols());
600 impl_->beginSolve(L, B);
601 detail::solve_lower(detail::exec_space{}, impl_->factor, impl_->work,
602 false);
603 detail::reserve_view(impl_->norms, static_cast<std::size_t>(B.cols()),
604 "gpr workspace norms");
605 detail::column_squared_norms(impl_->work, impl_->norms);
606 Eigen::VectorXd result;
607 detail::to_eigen(impl_->norms, result);
608 impl_->stats.result_download_bytes += detail::byte_count(result.size());
609 return result;
610}
611
613{
614 ensureState();
615 std::lock_guard<std::mutex> lock(impl_->mutex);
616 if (L.rows() != L.cols())
617 throw std::invalid_argument("Kokkos inverse requires a square factor");
618 const auto n = static_cast<std::size_t>(
619 detail::kokkosSolverExtent(static_cast<std::size_t>(L.rows())));
620 impl_->rejectFinalized();
621 if (n == 0) return EigenMatrix(0, 0);
623 impl_->requireRuntime();
624 impl_->bindFactor(L);
625 detail::reserve_view(impl_->work, n, n, "gpr workspace inverse root");
626 detail::reserve_view(impl_->product, n, n, "gpr workspace inverse");
627 detail::cholesky_inverse_on_device(impl_->factor, impl_->work,
628 impl_->product);
629 return impl_->download(impl_->product);
630}
631
633{
634 ensureState();
635 std::lock_guard<std::mutex> lock(impl_->mutex);
636 return impl_->stats;
637}
638
640{
641 ensureState();
642 std::lock_guard<std::mutex> lock(impl_->mutex);
643 impl_->stats = KokkosTransferStats{};
644}
645
647{
648 ensureState();
649 std::lock_guard<std::mutex> lock(impl_->mutex);
650 impl_->release();
651}
652
653KokkosFactor::KokkosFactor(const EigenMatrix& factor) : order_(factor.rows())
654{
655 if (factor.rows() != factor.cols())
656 throw std::invalid_argument("Kokkos factor must be square");
657 detail::kokkosSolverExtent(static_cast<std::size_t>(order_));
658 auto& state = workspace_.ensureState();
659 std::lock_guard<std::mutex> lock(state.mutex);
660 state.rejectFinalized();
661 if (order_ == 0) return;
662 state.requireRuntime();
663 state.bindFactor(factor);
664 // An immutable owner does not need a host witness for later queries.
665 state.witness.resize(0, 0);
666}
667
668KokkosFactor::KokkosFactor(const detail::KokkosDeviceFactor& supplied)
669 : order_(supplied.view.extent(0))
670{
671 if (supplied.view.extent(1) != supplied.view.extent(0))
672 throw std::invalid_argument("Kokkos factor must be square");
673 detail::kokkosSolverExtent(static_cast<std::size_t>(order_));
674 auto& state = workspace_.ensureState();
675 std::lock_guard<std::mutex> lock(state.mutex);
676 state.rejectFinalized();
677 state.requireRuntime();
678 state.factor = supplied.view;
679 state.resident = true;
680}
681
683{
684 auto& state = workspace_.ensureState();
685 std::lock_guard<std::mutex> lock(state.mutex);
686 state.rejectFinalized();
687 if (order_ <= 0) return 0.0;
689 // Same reduction as log_det_cholesky. The tiled device sum is a
690 // different association and does not have the Eigen factor's bits.
691 const auto factor = state.factor;
692 const Eigen::Index n = order_;
693 const Eigen::Index leading =
694 static_cast<Eigen::Index>(factor.stride(1));
695 Eigen::Map<const EigenMatrix, Eigen::Unaligned,
696 Eigen::OuterStride<Eigen::Dynamic>>
697 host(factor.data(), n, n,
698 Eigen::OuterStride<Eigen::Dynamic>(leading));
699 return host.diagonal().array().log().sum();
700 }
701 const auto factor = state.factor;
702 const int n = order_;
703 constexpr int kTile = 256;
704 const int n_tiles = (n + kTile - 1) / kTile;
705 detail::device_vector_t tiles(
706 Kokkos::view_alloc(Kokkos::WithoutInitializing,
707 "gpr resident logdet tiles"),
708 static_cast<std::size_t>(n_tiles));
709 detail::device_vector_t total_view(
710 Kokkos::view_alloc(Kokkos::WithoutInitializing,
711 "gpr resident logdet scalar"),
712 1);
713 Kokkos::parallel_for(
714 "gpr resident log determinant tiles",
715 Kokkos::RangePolicy<detail::exec_space>(0, n_tiles),
716 KOKKOS_LAMBDA(const int t) {
717 const int begin = t * kTile;
718 const int end = (begin + kTile < n) ? (begin + kTile) : n;
719 double sum = 0.0, corr = 0.0;
720 for (int row = begin; row < end; ++row) {
721 const double term = Kokkos::log(factor(row, row));
722 const double next = sum + term;
723 corr += Kokkos::abs(sum) >= Kokkos::abs(term)
724 ? (sum - next) + term
725 : (term - next) + sum;
726 sum = next;
727 }
728 tiles(t) = sum + corr;
729 });
730 Kokkos::parallel_for(
731 "gpr resident log determinant fold",
732 Kokkos::RangePolicy<detail::exec_space>(0, 1),
733 KOKKOS_LAMBDA(const int) {
734 double sum = 0.0, corr = 0.0;
735 for (int t = 0; t < n_tiles; ++t) {
736 const double term = tiles(t);
737 const double next = sum + term;
738 corr += Kokkos::abs(sum) >= Kokkos::abs(term)
739 ? (sum - next) + term
740 : (term - next) + sum;
741 sum = next;
742 }
743 total_view(0) = sum + corr;
744 });
745 double result = 0.0;
746 Kokkos::View<double, Kokkos::HostSpace,
747 Kokkos::MemoryTraits<Kokkos::Unmanaged>>
748 host(&result);
749 detail::audited_deep_copy(host, Kokkos::subview(total_view, 0),
750 sizeof(double), detail::CopyRole::ToHost);
751 state.stats.result_download_bytes += sizeof(double);
752 return result;
753}
754
756{
757 auto& state = *workspace_.impl_;
758 std::lock_guard<std::mutex> lock(state.mutex);
759 state.rejectFinalized();
760 if (order_ <= 0) return 0.0;
761 const auto factor = state.factor;
762 const int n = order_;
763 double squares = 0.0;
764 Kokkos::parallel_reduce(
765 "gpr resident factor frobenius norm",
766 Kokkos::RangePolicy<detail::exec_space>(0, n),
767 KOKKOS_LAMBDA(const int row, double& sum) {
768 double partial = 0.0;
769 for (int column = 0; column <= row; ++column)
770 partial += factor(row, column) * factor(row, column);
771 sum += partial;
772 },
773 squares);
774 state.stats.result_download_bytes += sizeof(double);
775 return std::sqrt(squares);
776}
777
779{
780 if (order_ <= 0) return std::numeric_limits<double>::epsilon();
781 const double frobenius = lowerFrobeniusNorm();
782 // Same residual bound as upperInverseNorm1. The column-sum lift alone
783 // leaves out the triangular-solve error.
784 const EigenMatrix identity = EigenMatrix::Identity(order_, order_);
785 const EigenMatrix inverse_columns = forward(identity);
786 const double infinity = std::numeric_limits<double>::infinity();
787 double inverse_norm = infinity;
788 if (inverse_columns.rows() == order_ && inverse_columns.cols() == order_ &&
789 inverse_columns.allFinite()) {
790 EigenMatrix factor(order_, order_);
791 {
792 auto& state = *workspace_.impl_;
793 std::lock_guard<std::mutex> lock(state.mutex);
794 state.rejectFinalized();
795 detail::to_eigen(state.factor, factor);
796 state.stats.result_download_bytes +=
797 detail::byte_count(factor.size());
798 }
799 factor.triangularView<Eigen::StrictlyUpper>().setZero();
800 if (factor.allFinite()) {
801 const double computed =
802 inverse_columns.cwiseAbs().colwise().sum().maxCoeff();
803 const EigenMatrix residual = identity - factor * inverse_columns;
804 const double residual_norm =
805 residual.allFinite()
806 ? residual.cwiseAbs().colwise().sum().maxCoeff()
807 : infinity;
808 const double factor_norm =
809 factor.cwiseAbs().colwise().sum().maxCoeff();
810 inverse_norm = upperInverseNorm1FromResidual(
811 computed, residual_norm, factor_norm, order_);
812 }
813 }
814 return choleskySchurRelativeError(order_, frobenius, inverse_norm);
815}
816
818{
819 auto& state = workspace_.ensureState();
820 std::lock_guard<std::mutex> lock(state.mutex);
821 if (!state.checkBoundSolve(rhs)) return EigenMatrix(order_, rhs.cols());
823 state.uploadRhs(rhs);
824 detail::solve_lower(detail::exec_space{}, state.factor, state.work, false);
825 return state.download(state.work);
826}
827
829{
830 auto& state = workspace_.ensureState();
831 std::lock_guard<std::mutex> lock(state.mutex);
832 if (!state.checkBoundSolve(rhs)) return EigenMatrix(order_, rhs.cols());
834 state.uploadRhs(rhs);
835 detail::solve_lower(detail::exec_space{}, state.factor, state.work, true);
836 return state.download(state.work);
837}
838
840{
841 auto& state = workspace_.ensureState();
842 std::lock_guard<std::mutex> lock(state.mutex);
843 if (!state.checkBoundSolve(rhs)) return EigenMatrix(order_, rhs.cols());
845 state.uploadRhs(rhs);
846 detail::solve_lower(detail::exec_space{}, state.factor, state.work, false);
847 detail::solve_lower(detail::exec_space{}, state.factor, state.work, true);
848 return state.download(state.work);
849}
850
851Eigen::VectorXd KokkosFactor::squaredNorms(const EigenMatrix& rhs) const
852{
853 auto& state = workspace_.ensureState();
854 std::lock_guard<std::mutex> lock(state.mutex);
855 if (!state.checkBoundSolve(rhs)) return Eigen::VectorXd::Zero(rhs.cols());
857 state.uploadRhs(rhs);
858 detail::solve_lower(detail::exec_space{}, state.factor, state.work, false);
859 detail::reserve_view(state.norms, static_cast<std::size_t>(rhs.cols()),
860 "gpr factor norms");
861 detail::column_squared_norms(state.work, state.norms);
862 Eigen::VectorXd result;
863 detail::to_eigen(state.norms, result);
864 state.stats.result_download_bytes += detail::byte_count(result.size());
865 return result;
866}
867
869{
870 auto& state = workspace_.ensureState();
871 std::lock_guard<std::mutex> lock(state.mutex);
872 state.rejectFinalized();
873 if (order_ == 0) return EigenMatrix(0, 0);
875 const auto n = static_cast<std::size_t>(order_);
876 detail::reserve_view(state.work, n, n, "gpr factor inverse root");
877 detail::reserve_view(state.product, n, n, "gpr factor inverse");
878 detail::cholesky_inverse_on_device(state.factor, state.work, state.product);
879 return state.download(state.product);
880}
881
883{
884 return workspace_.transferStats();
885}
886
888{
889 workspace_.resetTransferStats();
890}
891
892} // namespace linalg
893} // namespace gpr
@ x
Definition Enums.h:28
Correctly rounded Schur-complement diagonals from Cholesky solves.
EigenMatrix backward(const EigenMatrix &rhs) const
EigenMatrix forward(const EigenMatrix &rhs) const
double halfLogDeterminant() const
EigenMatrix inverse() const
double lowerFrobeniusNorm() const
||L||_F over the lower triangle, reduced on the device.
KokkosFactor(const EigenMatrix &factor)
Eigen::VectorXd squaredNorms(const EigenMatrix &rhs) const
EigenMatrix solve(const EigenMatrix &rhs) const
double schurRelativeError() const
KokkosTransferStats transferStats() const
EigenMatrix forward(const EigenMatrix &factor, const EigenMatrix &rhs)
L X = B.
EigenMatrix inverse(const EigenMatrix &factor)
(L L^T)^{-1}, formed on the device from the resident factor.
void resetTransferStats()
Zeroes the counters; the resident factor is kept.
EigenMatrix solve(const EigenMatrix &factor, const EigenMatrix &rhs)
L L^T X = B with one right-hand-side upload and one result download.
KokkosTransferStats transferStats() const
void clear()
Releases the resident factor and all device buffers; counters are kept.
Eigen::VectorXd squaredNorms(const EigenMatrix &factor, const EigenMatrix &rhs)
Squared column norms of L^{-1} B; only the norms are downloaded.
EigenMatrix backward(const EigenMatrix &factor, const EigenMatrix &rhs)
L^T X = B.
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void teamSolveLowerVector(const double *lower, std::int64_t lda, bool lower_factor, double *rhs, std::int64_t n)
EigenMatrix back_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L,...
void teamSolveLower(const double *lower, std::int64_t lda, bool lower_factor, double *rhs, std::int64_t ldb, std::int64_t n, std::int64_t cols)
Eigen::VectorXd forward_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
Forward triangular solve with vector RHS (BLAS equivalent: dtrsv).
double choleskySchurRelativeError(Eigen::Index order, double factor_frobenius_norm, double inverse_norm1) noexcept
Relative forward error of a Schur complement computed from a rounded Cholesky factor and triangular s...
Definition ExactSchur.h:259
bool kokkosHostExecutionMemory() noexcept
bool teamPanelKernels() noexcept
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
void teamSymmetricGram(const double *b, std::int64_t ldb, double *c, std::int64_t ldc, std::int64_t n)
bool trainingCholeskyLower(ProductMatrix lower)
Eigen::VectorXd forward_solve_mat_colwise_squared_norm(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve followed by columnwise squared norms.
bool teamCholeskyLower(double *lower, std::int64_t lda, std::int64_t n)
double upperInverseNorm1FromResidual(double computed_norm, double residual_norm, double factor_abs_norm, Eigen::Index order) noexcept
Upper bound on ||L^-1||_1 from a computed triangular solve.
Definition ExactSchur.h:310
double log_det_cholesky(const EigenMatrix &L)
Half log-determinant from Cholesky factor.
Eigen::VectorXd back_solve(const EigenMatrix &L, const Eigen::VectorXd &b)
Back triangular solve with vector RHS (BLAS equivalent: dtrsv).
double trace_product(const EigenMatrix &A, const EigenMatrix &B)
Frobenius inner product / trace of matrix product.
Eigen::VectorXd bordered_cholesky_diagonal(const EigenMatrix &L, const EigenMatrix &B, const Eigen::VectorXd &prior)
Posterior diagonal from bordered Cholesky pivots.
EigenMatrix cholesky_inverse(const EigenMatrix &L)
Symmetric inverse from Cholesky factor (LAPACK equivalent: dpotri).
bool trainingCholeskySelected(Eigen::Index order)
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
Cholesky decomposition (LAPACK equivalent: dpotrf).
void resetKokkosTransferAuditStats() noexcept
Eigen::VectorXd borderedCholeskyDiagonal(const Eigen::VectorXd &prior, const Eigen::MatrixBase< Derived > &whitened)
borderedCholeskyDiagonal for a whitened block L^-1 K_tq with no factor in hand: the allowance is the ...
Definition ExactSchur.h:444
KokkosTransferAuditStats kokkosTransferAuditStats() noexcept
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
KokkosTransferDirectionStats device_to_device
KokkosTransferDirectionStats host_to_host
KokkosTransferDirectionStats device_to_host
KokkosTransferDirectionStats boundary_to_execution
KokkosTransferDirectionStats host_to_device
KokkosTransferDirectionStats boundary_to_host
void uploadRhs(const EigenMatrix &rhs)
void bindFactor(const EigenMatrix &supplied)
bool checkSolve(const EigenMatrix &L, const EigenMatrix &B) const
EigenMatrix download(const detail::device_matrix_t &source)
bool checkBoundSolve(const EigenMatrix &B) const
void beginSolve(const EigenMatrix &L, const EigenMatrix &B)