Loading...
Searching...
No Matches
KokkosDensePosterior.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3#ifndef GPR_LINALG_KOKKOS_DENSE_POSTERIOR_H_
4#define GPR_LINALG_KOKKOS_DENSE_POSTERIOR_H_
5
6#include <KokkosBlas3_gemm.hpp>
7#include <Kokkos_Core.hpp>
8#include <array>
9#include <cmath>
10#include <cstddef>
11#include <functional>
12#include <limits>
13#include <memory>
14#include <stdexcept>
15#include <string>
16#include <utility>
17#include <vector>
18
19#include "KokkosAuditedCopy.h"
20#include "KokkosPow2Scale.h"
21
22namespace gpr::linalg::detail {
23
24struct TransferCounters {
25 std::size_t bulk_host_to_device = 0;
26 std::size_t bulk_device_to_host = 0;
27 std::size_t scalar_device_to_host_bytes = 0;
28};
29
30template <class ExecutionSpace, class Scalar = double>
32class KokkosDensePosterior {
33public:
34 using execution_space = ExecutionSpace;
35 using scalar_type = Scalar;
36 using memory_space = typename execution_space::memory_space;
37 using device_type = Kokkos::Device<execution_space, memory_space>;
38 using matrix_type =
39 Kokkos::View<scalar_type**, Kokkos::LayoutLeft, device_type>;
40 using const_matrix_type =
41 Kokkos::View<const scalar_type**, Kokkos::LayoutLeft, device_type>;
42 using vector_type = Kokkos::View<scalar_type*, device_type>;
43 using const_vector_type = Kokkos::View<const scalar_type*, device_type>;
44
45 using Factorize =
46 std::function<bool(const execution_space&, const matrix_type&)>;
47 using SolveLower =
48 std::function<void(const execution_space&, const matrix_type&,
49 const matrix_type&, bool transpose)>;
50
51private:
52 struct DeviceState {
53 matrix_type factor;
54 vector_type alpha;
55 vector_type whitened_targets;
56 vector_type scale;
57 vector_type inverse_diagonal;
58 matrix_type rhs;
59 vector_type mean;
60 vector_type variance;
61 const_matrix_type prediction_cross;
62 const_vector_type prediction_prior;
63 matrix_type objective;
64 Kokkos::View<scalar_type*, device_type> scalar_workspace;
65 Kokkos::View<int, device_type> status_workspace;
66 std::vector<matrix_type> retired_matrices;
67 std::vector<vector_type> retired_vectors;
68 std::vector<Kokkos::View<int, device_type>> retired_status;
69 bool valid = false;
70 bool objective_valid = false;
71 scalar_type objective_data_term_scale = scalar_type(1);
72 std::size_t rows = 0;
73
74 void invalidate_preserving_allocations()
75 {
76 valid = false;
77 objective_valid = false;
78 rows = 0;
79 retire(factor);
80 retire(alpha);
81 retire(whitened_targets);
82 retire(scale);
83 retire(inverse_diagonal);
84 retire(rhs);
85 retire(mean);
86 retire(variance);
87 retire(objective);
88 retire(scalar_workspace);
89 if (status_workspace.data()) {
90 retired_status.push_back(status_workspace);
91 status_workspace = Kokkos::View<int, device_type>();
92 }
93 }
94
95 void retire_prediction_storage()
96 {
97 prediction_cross = const_matrix_type();
98 prediction_prior = const_vector_type();
99 retire(rhs);
100 retire(mean);
101 retire(variance);
102 }
103
104 void retire_objective_storage()
105 {
106 retire(objective);
107 }
108
109 void clear_retired()
110 {
111 retired_matrices.clear();
112 retired_vectors.clear();
113 retired_status.clear();
114 }
115
116 void release() noexcept
117 {
118 valid = false;
119 objective_valid = false;
120 rows = 0;
121 factor = matrix_type();
122 alpha = vector_type();
123 whitened_targets = vector_type();
124 scale = vector_type();
125 inverse_diagonal = vector_type();
126 rhs = matrix_type();
127 mean = vector_type();
128 variance = vector_type();
129 prediction_cross = const_matrix_type();
130 prediction_prior = const_vector_type();
131 objective = matrix_type();
132 scalar_workspace = Kokkos::View<scalar_type*, device_type>();
133 status_workspace = Kokkos::View<int, device_type>();
134 retired_matrices.clear();
135 retired_vectors.clear();
136 retired_status.clear();
137 }
138
139 private:
140 void retire(matrix_type& view)
141 {
142 if (view.data()) retired_matrices.push_back(view);
143 view = matrix_type();
144 }
145 void retire(vector_type& view)
146 {
147 if (view.data()) retired_vectors.push_back(view);
148 view = vector_type();
149 }
150 };
151
152public:
153 KokkosDensePosterior(execution_space exec, Factorize factorize,
154 SolveLower solve_lower,
155 TransferCounters* counters = nullptr)
156 : exec_(std::move(exec)),
157 factorize_(std::move(factorize)),
158 solve_lower_(std::move(solve_lower)),
159 counters_(counters),
160 state_(std::make_shared<DeviceState>())
161 {
162 if (!runtime_alive()) {
163 throw std::runtime_error(
164 "KokkosDensePosterior requires an initialized Kokkos runtime");
165 }
166 if (!factorize_ || !solve_lower_) {
167 throw std::invalid_argument(
168 "KokkosDensePosterior requires factorize and solve_lower");
169 }
170
171 std::weak_ptr<DeviceState> weak = state_;
172 Kokkos::push_finalize_hook([weak, execution = exec_]() noexcept {
173 execution.fence("gpr finalize resident posterior");
174 if (auto state = weak.lock()) state->release();
175 });
176 }
177
178 KokkosDensePosterior(const KokkosDensePosterior&) = delete;
179 KokkosDensePosterior& operator=(const KokkosDensePosterior&) = delete;
180 KokkosDensePosterior(KokkosDensePosterior&&) noexcept = default;
181 KokkosDensePosterior& operator=(KokkosDensePosterior&&) = delete;
182 ~KokkosDensePosterior()
183 {
184 if (state_ && runtime_alive()) {
185 exec_.fence("gpr destroy resident posterior");
186 state_->release();
187 }
188 }
189
190 scalar_type condition(
191 const const_matrix_type& covariance, const const_vector_type& targets,
192 const const_vector_type& noise_variance,
193 const const_vector_type& constant_vector = const_vector_type(),
194 scalar_type jitter = scalar_type(0))
195 {
196 if (!runtime_alive()) {
197 state_->valid = false;
198 return infinity();
199 }
200
201 // A failed attempt must not leave an earlier posterior usable.
202 exec_.fence("gpr recycle resident conditioning buffers");
203 state_->clear_retired();
204 state_->invalidate_preserving_allocations();
205
206 const std::size_t n = covariance.extent(0);
207 const bool have_u = constant_vector.extent(0) != 0;
208 if (covariance.extent(1) != n || targets.extent(0) != n ||
209 noise_variance.extent(0) != n ||
210 (have_u && constant_vector.extent(0) != n) || n == 0 ||
211 !finite_nonnegative(jitter)) {
212 return infinity();
213 }
214
215 try {
216 allocate_condition_workspace(n);
217
218 const auto factor = state_->factor;
219 const auto scale = state_->scale;
220
221 Kokkos::parallel_for(
222 "resident_gp_form_covariance",
223 Kokkos::MDRangePolicy<execution_space, Kokkos::Rank<2>>(
224 exec_, {0, 0}, {n, n}),
225 KOKKOS_LAMBDA(const std::size_t i, const std::size_t j) {
226 scalar_type value = covariance(i, j);
227 if (have_u)
228 value += constant_vector(i) * constant_vector(j);
229 if (i == j) value += noise_variance(i) + jitter;
230 factor(i, j) = value;
231 });
232
233 const auto status = state_->status_workspace;
234 Kokkos::parallel_reduce(
235 "resident_gp_check_diagonal",
236 Kokkos::RangePolicy<execution_space>(exec_, 0, n),
237 KOKKOS_LAMBDA(const std::size_t i, int& bad) {
238 const scalar_type d = factor(i, i);
239 const scalar_type v = noise_variance(i);
240 const bool finite =
241 (d == d) &&
242 (d < std::numeric_limits<scalar_type>::infinity());
243 const bool variance_valid =
244 (v == v) && (v >= scalar_type(0)) &&
245 (v < std::numeric_limits<scalar_type>::infinity());
246 if (!(d > scalar_type(0)) || !finite || !variance_valid) {
247 bad += 1;
248 scale(i) = scalar_type(1);
249 } else {
250 const int exponent = pow2::ilogb(d);
251 const int half = exponent >= 0 ? exponent / 2
252 : -((-exponent + 1) / 2);
253 scale(i) = pow2::scalbn(scalar_type(1), half);
254 }
255 },
256 status);
257
258 int bad_diagonal = 0;
259 copy_scalar_to_host(status, bad_diagonal);
260 if (bad_diagonal != 0) {
261 state_->release();
262 return infinity();
263 }
264
265 Kokkos::parallel_for(
266 "resident_gp_equilibrate",
267 Kokkos::MDRangePolicy<execution_space, Kokkos::Rank<2>>(
268 exec_, {0, 0}, {n, n}),
269 KOKKOS_LAMBDA(const std::size_t i, const std::size_t j) {
270 factor(i, j) =
271 pow2::scalbn(factor(i, j), -pow2::ilogb(scale(i)) -
272 pow2::ilogb(scale(j)));
273 });
274
275 if (!factorize_(exec_, factor)) {
276 state_->release();
277 return infinity();
278 }
279
280 Kokkos::parallel_for(
281 "resident_gp_restore_physical_factor",
282 Kokkos::MDRangePolicy<execution_space, Kokkos::Rank<2>>(
283 exec_, {0, 0}, {n, n}),
284 KOKKOS_LAMBDA(const std::size_t i, const std::size_t j) {
285 factor(i, j) =
286 (j <= i) ? scale(i) * factor(i, j) : scalar_type(0);
287 });
288
289 auto rhs = state_->rhs;
290 Kokkos::parallel_for(
291 "resident_gp_copy_targets",
292 Kokkos::RangePolicy<execution_space>(exec_, 0, n),
293 KOKKOS_LAMBDA(const std::size_t i) { rhs(i, 0) = targets(i); });
294
295 solve_lower_(exec_, factor, rhs, false);
296 const auto whitened = state_->whitened_targets;
297 Kokkos::parallel_for(
298 "resident_gp_save_whitened_targets",
299 Kokkos::RangePolicy<execution_space>(exec_, 0, n),
300 KOKKOS_LAMBDA(const std::size_t i) {
301 whitened(i) = rhs(i, 0);
302 });
303
304 solve_lower_(exec_, factor, rhs, true);
305 const auto alpha = state_->alpha;
306 Kokkos::parallel_for(
307 "resident_gp_save_alpha",
308 Kokkos::RangePolicy<execution_space>(exec_, 0, n),
309 KOKKOS_LAMBDA(const std::size_t i) { alpha(i) = rhs(i, 0); });
310
311 const auto stats = state_->scalar_workspace;
312 reduce_objective_stats(factor, whitened, n, stats);
313
314 scalar_type host_stats[2] = {};
315 using host_unmanaged =
316 Kokkos::View<scalar_type*, Kokkos::HostSpace,
317 Kokkos::MemoryTraits<Kokkos::Unmanaged>>;
318 host_unmanaged host_view(host_stats, 2);
319 audited_deep_copy(exec_, host_view, stats, CopyRole::ToHost);
320 if (counters_)
321 counters_->scalar_device_to_host_bytes +=
322 2 * sizeof(scalar_type);
323 exec_.fence("resident_gp_condition_scalar_results");
324
325 const scalar_type pi = std::acos(scalar_type(-1));
326 const scalar_type nll = host_stats[0] +
327 scalar_type(0.5) * host_stats[1] +
328 scalar_type(0.5) * scalar_type(n) *
329 std::log(scalar_type(2) * pi);
330 if (!std::isfinite(nll)) {
331 state_->release();
332 return infinity();
333 }
334 state_->clear_retired();
335 state_->valid = true;
336 state_->rows = n;
337 return nll;
338 } catch (...) {
339 if (runtime_alive()) state_->release();
340 throw;
341 }
342 }
343
344 // Convenience for homoscedastic noise. The temporary is a device View and
345 // is filled on the supplied execution-space instance.
346 scalar_type condition(
347 const const_matrix_type& covariance, const const_vector_type& targets,
348 scalar_type noise_variance,
349 const const_vector_type& constant_vector = const_vector_type(),
350 scalar_type jitter = scalar_type(0))
351 {
352 if (!runtime_alive()) {
353 state_->valid = false;
354 return infinity();
355 }
356 if (!finite_nonnegative(noise_variance)) {
357 exec_.fence("gpr recycle resident conditioning buffers");
358 state_->clear_retired();
359 state_->invalidate_preserving_allocations();
360 return infinity();
361 }
362 const std::size_t n = covariance.extent(0);
363 vector_type variance("resident_gp_constant_noise", n);
364 audited_deep_copy(exec_, variance, noise_variance);
365 return condition(covariance, targets, const_vector_type(variance),
366 constant_vector, jitter);
367 }
368
369 std::array<scalar_type, 2> objective_parts()
370 {
371 require_valid("objective_parts");
372 const auto factor = state_->factor;
373 const auto whitened = state_->whitened_targets;
374 const auto stats = state_->scalar_workspace;
375 const std::size_t n = state_->rows;
376 reduce_objective_stats(factor, whitened, n, stats);
377 std::array<scalar_type, 2> result{};
378 Kokkos::View<scalar_type*, Kokkos::HostSpace,
379 Kokkos::MemoryTraits<Kokkos::Unmanaged>>
380 host(result.data(), 2);
381 audited_deep_copy(exec_, host, stats, CopyRole::ToHost);
382 exec_.fence("gpr resident objective report");
383 if (counters_)
384 counters_->scalar_device_to_host_bytes += 2 * sizeof(scalar_type);
385 return result;
386 }
387
388 vector_type inverse_diagonal()
389 {
390 if (!state_->objective_valid) objective_weight();
391 return state_->inverse_diagonal;
392 }
393
394 // Border a physical factor through a device Schur complement. Numerical
395 // rejection preserves the owned factor and its posterior coefficients.
396 scalar_type append(const const_matrix_type& cross,
397 const const_matrix_type& diagonal,
398 const const_vector_type& targets)
399 {
400 require_valid("append");
401 const std::size_t old = state_->rows, extra = diagonal.extent(0);
402 if (extra == 0 || diagonal.extent(1) != extra ||
403 cross.extent(0) != old || cross.extent(1) != extra ||
404 targets.extent(0) != old + extra)
405 throw std::invalid_argument(
406 "append extents do not match posterior");
407 exec_.fence("gpr prepare resident border");
408 matrix_type projected("resident_gp_projected_border", old, extra);
409 matrix_type schur("resident_gp_schur", extra, extra);
410 audited_deep_copy(exec_, projected, cross, CopyRole::Internal);
411 audited_deep_copy(exec_, schur, diagonal, CopyRole::Internal);
412 solve_lower_(exec_, state_->factor, projected, false);
413 {
414 const KokkosCopyScope kernels(KokkosCopyContext::ThirdParty);
415 KokkosBlas::gemm(exec_, "T", "N", scalar_type(-1), projected,
416 projected, scalar_type(1), schur);
417 }
418 KokkosDensePosterior border(exec_, factorize_, solve_lower_, counters_);
419 vector_type zero("resident_gp_border_zero", extra);
420 const scalar_type accepted =
421 border.condition(schur, zero, scalar_type(0));
422 if (!std::isfinite(accepted)) return infinity();
423 const std::size_t n = old + extra;
424 matrix_type combined("resident_gp_bordered_factor", n, n);
425 const auto lower = state_->factor, tail = border.factor();
426 Kokkos::parallel_for(
427 "resident_gp_join_factor",
428 Kokkos::MDRangePolicy<execution_space, Kokkos::Rank<2>>(
429 exec_, {0, 0}, {n, n}),
430 KOKKOS_LAMBDA(const std::size_t i, const std::size_t j) {
431 combined(i, j) = j > i ? scalar_type(0)
432 : i < old ? lower(i, j)
433 : j < old ? projected(j, i - old)
434 : tail(i - old, j - old);
435 });
436 exec_.fence("gpr commit resident bordered factor");
437 state_->clear_retired();
438 state_->invalidate_preserving_allocations();
439 allocate_condition_workspace(n, combined);
440 state_->rows = n;
441 state_->valid = true;
442 set_targets(targets);
443 const auto parts = objective_parts();
444 return parts[0] + scalar_type(.5) * parts[1] +
445 scalar_type(.5) * n *
446 std::log(scalar_type(2) * std::acos(scalar_type(-1)));
447 }
448
449 void set_targets(const const_vector_type& targets)
450 {
451 require_valid("set_targets");
452 const std::size_t n = state_->rows;
453 if (targets.extent(0) != n)
454 throw std::invalid_argument(
455 "target extent does not match posterior");
456 exec_.fence("gpr refresh resident targets");
457 state_->objective_valid = false;
458 state_->rhs = matrix_type("resident_gp_target_rhs", n, 1);
459 const auto rhs = state_->rhs;
460 const auto whitened = state_->whitened_targets;
461 const auto alpha = state_->alpha;
462 Kokkos::parallel_for(
463 "resident_gp_copy_targets",
464 Kokkos::RangePolicy<execution_space>(exec_, 0, n),
465 KOKKOS_LAMBDA(const std::size_t row) {
466 rhs(row, 0) = targets(row);
467 });
468 solve_lower_(exec_, state_->factor, rhs, false);
469 Kokkos::parallel_for(
470 "resident_gp_save_whitened_targets",
471 Kokkos::RangePolicy<execution_space>(exec_, 0, n),
472 KOKKOS_LAMBDA(const std::size_t row) {
473 whitened(row) = rhs(row, 0);
474 });
475 solve_lower_(exec_, state_->factor, rhs, true);
476 Kokkos::parallel_for(
477 "resident_gp_save_coefficients",
478 Kokkos::RangePolicy<execution_space>(exec_, 0, n),
479 KOKKOS_LAMBDA(const std::size_t row) { alpha(row) = rhs(row, 0); });
480 }
481
488 void predict(const const_matrix_type& cross_covariance,
489 const const_vector_type& prior_diagonal,
490 bool with_variance = true, bool stable_variance = false)
491 {
492 require_valid("predict");
493 const std::size_t n = state_->rows;
494 const std::size_t q = cross_covariance.extent(1);
495 if (cross_covariance.extent(0) != n || prior_diagonal.extent(0) != q) {
496 throw std::invalid_argument("predict input extents do not match");
497 }
498
499 exec_.fence("gpr recycle resident prediction buffers");
500 state_->clear_retired();
501 state_->retire_prediction_storage();
502 state_->prediction_cross = cross_covariance;
503 state_->prediction_prior = prior_diagonal;
504 state_->mean = vector_type("resident_gp_predict_mean", q);
505 if (!with_variance) {
506 state_->rhs = matrix_type();
507 state_->variance = vector_type();
508 const auto alpha = state_->alpha;
509 const auto mean = state_->mean;
510 Kokkos::parallel_for(
511 "resident_gp_prediction_mean",
512 Kokkos::RangePolicy<execution_space>(exec_, 0, q),
513 KOKKOS_LAMBDA(const std::size_t j) {
514 scalar_type m = 0, correction = 0;
515 for (std::size_t i = 0; i < n; ++i) {
516 const scalar_type value =
517 cross_covariance(i, j) * alpha(i);
518 const scalar_type sum = m + value;
519 correction += Kokkos::abs(m) >= Kokkos::abs(value)
520 ? (m - sum) + value
521 : (value - sum) + m;
522 m = sum;
523 }
524 mean(j) = m + correction;
525 });
526 return;
527 }
528 state_->rhs = matrix_type("resident_gp_predict_rhs", n, q);
529 state_->variance = vector_type("resident_gp_predict_variance", q);
530
531 const auto rhs = state_->rhs;
532 audited_deep_copy(exec_, rhs, cross_covariance, CopyRole::Internal);
533 solve_lower_(exec_, state_->factor, rhs, false);
534
535 const auto alpha = state_->alpha;
536 const auto mean = state_->mean;
537 const auto variance = state_->variance;
538 Kokkos::parallel_for(
539 "resident_gp_prediction",
540 Kokkos::RangePolicy<execution_space>(exec_, 0, q),
541 KOKKOS_LAMBDA(const std::size_t j) {
542 scalar_type m = 0, correction = 0;
543 scalar_type reduction = 0, norm_correction = 0;
544 scalar_type pivot = prior_diagonal(j), pivot_correction = 0;
545 for (std::size_t i = 0; i < n; ++i) {
546 const scalar_type value = cross_covariance(i, j) * alpha(i);
547 const scalar_type sum = m + value;
548 correction += Kokkos::abs(m) >= Kokkos::abs(value)
549 ? (m - sum) + value
550 : (value - sum) + m;
551 m = sum;
552 const scalar_type square = rhs(i, j) * rhs(i, j);
553 const scalar_type norm_sum = reduction + square;
554 norm_correction +=
555 Kokkos::abs(reduction) >= Kokkos::abs(square)
556 ? (reduction - norm_sum) + square
557 : (square - norm_sum) + reduction;
558 reduction = norm_sum;
559 if (stable_variance) {
560 const scalar_type negative_square = -square;
561 const scalar_type pivot_sum = pivot + negative_square;
562 pivot_correction +=
563 Kokkos::abs(pivot) >= Kokkos::abs(negative_square)
564 ? (pivot - pivot_sum) + negative_square
565 : (negative_square - pivot_sum) + pivot;
566 pivot_correction -=
567 Kokkos::fma(rhs(i, j), rhs(i, j), -square);
568 pivot = pivot_sum;
569 }
570 }
571 mean(j) = m + correction;
572 variance(j) =
573 stable_variance
574 ? pivot + pivot_correction
575 : prior_diagonal(j) - (reduction + norm_correction);
576 });
577 }
578
579 matrix_type objective_weight(scalar_type data_term_scale = scalar_type(1))
580 {
581 require_valid("objective_weight");
582 const std::size_t n = state_->rows;
583 if (state_->objective_valid &&
584 state_->objective_data_term_scale == data_term_scale)
585 return state_->objective;
586 exec_.fence("gpr recycle resident objective buffers");
587 state_->clear_retired();
588 state_->retire_objective_storage();
589 state_->objective = matrix_type("resident_gp_objective_weight", n, n);
590 auto weight = state_->objective;
591
592 Kokkos::parallel_for(
593 "resident_gp_identity",
594 Kokkos::MDRangePolicy<execution_space, Kokkos::Rank<2>>(
595 exec_, {0, 0}, {n, n}),
596 KOKKOS_LAMBDA(const std::size_t i, const std::size_t j) {
597 weight(i, j) = (i == j) ? scalar_type(1) : scalar_type(0);
598 });
599 solve_lower_(exec_, state_->factor, weight, false);
600 solve_lower_(exec_, state_->factor, weight, true);
601
602 const auto alpha = state_->alpha;
603 state_->inverse_diagonal =
604 vector_type("resident_gp_inverse_diagonal", n);
605 const auto inverse_diagonal = state_->inverse_diagonal;
606 Kokkos::parallel_for(
607 "resident_gp_finish_objective_weight",
608 Kokkos::MDRangePolicy<execution_space, Kokkos::Rank<2>>(
609 exec_, {0, 0}, {n, n}),
610 KOKKOS_LAMBDA(const std::size_t i, const std::size_t j) {
611 if (i == j) inverse_diagonal(i) = weight(i, j);
612 weight(i, j) =
613 scalar_type(0.5) *
614 (weight(i, j) - data_term_scale * alpha(i) * alpha(j));
615 });
616 state_->objective_data_term_scale = data_term_scale;
617 state_->objective_valid = true;
618 return weight;
619 }
620
621 bool valid() const noexcept
622 {
623 return runtime_alive() && state_ && state_->valid;
624 }
625 std::size_t rows() const noexcept
626 {
627 return valid() ? state_->rows : 0;
628 }
629
630 matrix_type factor() const noexcept
631 {
632 return state_ ? state_->factor : matrix_type();
633 }
634 vector_type alpha() const noexcept
635 {
636 return state_ ? state_->alpha : vector_type();
637 }
638 vector_type whitened_targets() const noexcept
639 {
640 return state_ ? state_->whitened_targets : vector_type();
641 }
642 vector_type mean() const noexcept
643 {
644 return state_ ? state_->mean : vector_type();
645 }
646 vector_type variance() const noexcept
647 {
648 return state_ ? state_->variance : vector_type();
649 }
650
651 TransferCounters transfer_counters() const noexcept
652 {
653 return counters_ ? *counters_ : TransferCounters{};
654 }
655
656 // CUDA refuses an extended __host__ __device__ lambda whose enclosing
657 // function has private or protected access, so this helper, whose
658 // reductions are such lambdas, is a public member. It is not part of
659 // the interface: only condition() and objective_parts() call it.
660 void reduce_objective_stats(
661 const matrix_type& factor, const vector_type& whitened, std::size_t n,
662 const Kokkos::View<scalar_type*, device_type>& stats)
663 {
664 if (n == 0) {
665 audited_deep_copy(exec_, stats, scalar_type(0));
666 return;
667 }
668 constexpr std::size_t kTile = 256;
669 const std::size_t n_tiles = (n + kTile - 1) / kTile;
670 matrix_type tiles(Kokkos::view_alloc(exec_, Kokkos::WithoutInitializing,
671 "resident_gp_objective_tiles"),
672 n_tiles, 2);
673 Kokkos::parallel_for(
674 "resident_gp_objective_tiles",
675 Kokkos::RangePolicy<execution_space>(exec_, 0, n_tiles),
676 KOKKOS_LAMBDA(const std::size_t t) {
677 const std::size_t begin = t * kTile;
678 const std::size_t end =
679 (begin + kTile < n) ? (begin + kTile) : n;
680 scalar_type ld_sum = 0, ld_corr = 0;
681 scalar_type q_sum = 0, q_corr = 0;
682 for (std::size_t i = begin; i < end; ++i) {
683 const scalar_type ld = Kokkos::log(factor(i, i));
684 const scalar_type ld_next = ld_sum + ld;
685 ld_corr += Kokkos::abs(ld_sum) >= Kokkos::abs(ld)
686 ? (ld_sum - ld_next) + ld
687 : (ld - ld_next) + ld_sum;
688 ld_sum = ld_next;
689
690 const scalar_type w = whitened(i);
691 const scalar_type q = w * w;
692 const scalar_type q_next = q_sum + q;
693 q_corr += Kokkos::abs(q_sum) >= Kokkos::abs(q)
694 ? (q_sum - q_next) + q
695 : (q - q_next) + q_sum;
696 q_sum = q_next;
697 }
698 tiles(t, 0) = ld_sum + ld_corr;
699 tiles(t, 1) = q_sum + q_corr;
700 });
701 Kokkos::parallel_for(
702 "resident_gp_objective_fold",
703 Kokkos::RangePolicy<execution_space>(exec_, 0, 2),
704 KOKKOS_LAMBDA(const std::size_t col) {
705 scalar_type sum = 0, corr = 0;
706 for (std::size_t t = 0; t < n_tiles; ++t) {
707 const scalar_type term = tiles(t, col);
708 const scalar_type next = sum + term;
709 corr += Kokkos::abs(sum) >= Kokkos::abs(term)
710 ? (sum - next) + term
711 : (term - next) + sum;
712 sum = next;
713 }
714 stats(col) = sum + corr;
715 });
716 }
717
718private:
719 bool runtime_alive() const noexcept
720 {
721 return Kokkos::is_initialized() && !Kokkos::is_finalized();
722 }
723
724 static scalar_type infinity() noexcept
725 {
726 return std::numeric_limits<scalar_type>::infinity();
727 }
728
729 static bool finite_nonnegative(scalar_type value) noexcept
730 {
731 return std::isfinite(value) && value >= scalar_type(0);
732 }
733
734 void require_valid(const char* operation) const
735 {
736 if (!runtime_alive()) {
737 throw std::runtime_error(std::string(operation) +
738 " called after Kokkos finalization");
739 }
740 if (!state_->valid) {
741 throw std::logic_error(std::string(operation) +
742 " requires a conditioned posterior");
743 }
744 }
745
746 void allocate_condition_workspace(std::size_t n,
747 matrix_type factor = matrix_type())
748 {
749 state_->factor =
750 factor.data() ? factor : matrix_type("resident_gp_factor", n, n);
751 state_->alpha = vector_type("resident_gp_alpha", n);
752 state_->whitened_targets =
753 vector_type("resident_gp_whitened_targets", n);
754 state_->scale = vector_type("resident_gp_scale", n);
755 state_->rhs = matrix_type("resident_gp_rhs", n, 1);
756 state_->scalar_workspace = Kokkos::View<scalar_type*, device_type>(
757 "resident_gp_scalar_workspace", 2);
758 state_->status_workspace =
759 Kokkos::View<int, device_type>("resident_gp_status_workspace");
760 }
761
762 template <class DeviceScalarView, class HostScalar>
763 void copy_scalar_to_host(const DeviceScalarView& source,
764 HostScalar& destination)
765 {
766 using host_scalar_view =
767 Kokkos::View<HostScalar, Kokkos::HostSpace,
768 Kokkos::MemoryTraits<Kokkos::Unmanaged>>;
769 host_scalar_view host_view(&destination);
770 audited_deep_copy(exec_, host_view, source, CopyRole::ToHost);
771 if (counters_)
772 counters_->scalar_device_to_host_bytes += sizeof(HostScalar);
773 exec_.fence("resident_gp_scalar_validation");
774 }
775
776 execution_space exec_;
777 Factorize factorize_;
778 SolveLower solve_lower_;
779 TransferCounters* counters_ = nullptr;
780 std::shared_ptr<DeviceState> state_;
781};
782
783} // namespace gpr::linalg::detail
784
785#endif
int status