Loading...
Searching...
No Matches
CusolverEigh.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "CusolverEigh.h"
6
7#include <dlfcn.h>
8
9#include <cstddef>
10#include <cstdio>
11#include <cstdlib>
12#include <limits>
13
14namespace gpr {
15namespace linalg {
16
17namespace {
18
19// Opaque CUDA / cuSOLVER handles are pointers.
20using cudaError_t = int;
21using cusolverStatus_t = int;
22using cusolverDnHandle_t = void*;
23
24// Enum values from the CUDA toolkit headers (stable across versions).
25constexpr int kCudaSuccess = 0;
26constexpr int kCudaMemcpyHostToDevice = 1;
27constexpr int kCudaMemcpyDeviceToHost = 2;
28constexpr int kCusolverStatusSuccess = 0;
29constexpr int kCusolverEigModeVector = 1; // CUSOLVER_EIG_MODE_VECTOR
30constexpr int kCublasFillModeLower = 0; // CUBLAS_FILL_MODE_LOWER
31
32// cudart entry points.
33using cudaMalloc_t = cudaError_t (*)(void**, std::size_t);
34using cudaFree_t = cudaError_t (*)(void*);
35using cudaMemcpy_t = cudaError_t (*)(void*, const void*, std::size_t, int);
36using cudaDeviceSynchronize_t = cudaError_t (*)();
37using cudaGetDeviceCount_t = cudaError_t (*)(int*);
38using cudaSetDevice_t = cudaError_t (*)(int);
39
40// cuSOLVER dense entry points.
41using cusolverDnCreate_t = cusolverStatus_t (*)(cusolverDnHandle_t*);
42using cusolverDnDestroy_t = cusolverStatus_t (*)(cusolverDnHandle_t);
43using cusolverDnDsyevd_bufferSize_t = cusolverStatus_t (*)(
44 cusolverDnHandle_t, int /*jobz*/, int /*uplo*/, int /*n*/,
45 const double* /*A*/, int /*lda*/, const double* /*W*/, int* /*lwork*/);
46using cusolverDnDsyevd_t = cusolverStatus_t (*)(cusolverDnHandle_t,
47 int /*jobz*/, int /*uplo*/,
48 int /*n*/, double* /*A*/,
49 int /*lda*/, double* /*W*/,
50 double* /*work*/, int /*lwork*/,
51 int* /*devInfo*/);
52
53// cuBLAS dense entry points (v2 API; handle is an opaque pointer, status
54// shares the 0 == success convention).
55using cublasHandle_t = void*;
56using cublasStatus_t = int;
57using cublasCreate_t = cublasStatus_t (*)(cublasHandle_t*);
58using cublasDestroy_t = cublasStatus_t (*)(cublasHandle_t);
59using cublasDtrsm_t = cublasStatus_t (*)(cublasHandle_t, int /*side*/,
60 int /*uplo*/, int /*trans*/,
61 int /*diag*/, int /*m*/, int /*n*/,
62 const double* /*alpha*/,
63 const double* /*A*/, int /*lda*/,
64 double* /*B*/, int /*ldb*/);
65using cublasDgemm_t = cublasStatus_t (*)(cublasHandle_t, int /*transa*/,
66 int /*transb*/, int /*m*/, int /*n*/,
67 int /*k*/, const double* /*alpha*/,
68 const double* /*A*/, int /*lda*/,
69 const double* /*B*/, int /*ldb*/,
70 const double* /*beta*/, double* /*C*/,
71 int /*ldc*/);
72constexpr int kCublasStatusSuccess = 0;
73constexpr int kCublasOpN = 0; // CUBLAS_OP_N
74
75// Loader/step chatter toggle; failures print regardless. Plain bool
76// (not atomic): set once from config wiring before first use.
77bool g_cusolver_eigh_verbose = false;
78
79} // namespace
80
81void CusolverEighLib::setVerbose(bool verbose) noexcept
82{
83 g_cusolver_eigh_verbose = verbose;
84}
85
87 void* cudart_handle = nullptr;
88 void* cusolver_handle = nullptr;
89
90 cudaMalloc_t cudaMalloc = nullptr;
91 cudaFree_t cudaFree = nullptr;
92 cudaMemcpy_t cudaMemcpy = nullptr;
93 cudaDeviceSynchronize_t cudaDeviceSynchronize = nullptr;
94 cudaGetDeviceCount_t cudaGetDeviceCount = nullptr;
95 cudaSetDevice_t cudaSetDevice = nullptr;
96
97 cusolverDnCreate_t cusolverDnCreate = nullptr;
98 cusolverDnDestroy_t cusolverDnDestroy = nullptr;
99 cusolverDnDsyevd_bufferSize_t cusolverDnDsyevd_bufferSize = nullptr;
100 cusolverDnDsyevd_t cusolverDnDsyevd = nullptr;
101
102 void* cublas_handle_lib = nullptr;
103 cublasCreate_t cublasCreate = nullptr;
104 cublasDestroy_t cublasDestroy = nullptr;
105 cublasDgemm_t cublasDgemm = nullptr;
107 // Process-lifetime cuBLAS context, created lazily on first gemmNN.
108 // Each cublasCreate allocates a fresh device workspace, which is
109 // per-append overhead the singleton pattern avoids; the driver
110 // reclaims it at process exit.
112 bool cublas_ctx_failed = false;
113
114 // Grow-only device scratch pool. Every solve/product previously
115 // paired a cudaMalloc with a cudaFree, so a run issued one
116 // allocation per buffer per call (measured: 14347 cudaMalloc plus
117 // 19796 cudaFree on one Baker cell). The buffers hold no state
118 // between calls -- each is fully overwritten by the host-to-device
119 // copy or by the kernel that writes it -- so a buffer large enough
120 // for the current call can simply be reused. Freed by the driver at
121 // process exit.
122 struct Scratch {
123 double* ptr = nullptr;
124 std::size_t bytes = 0;
125 };
128 // The resident triangular factor of trsmLowerResident and the epoch
129 // and order it was uploaded for.
131 std::uint64_t trsm_epoch = 0;
132 int trsm_n = 0;
133 bool trsm_resident = false;
134 cublasDtrsm_t cublasDtrsm = nullptr;
135
138 bool reserve(Scratch& s, std::size_t bytes)
139 {
140 if (bytes == 0) return true;
141 if (s.ptr != nullptr && s.bytes >= bytes) return true;
142 if (s.ptr != nullptr) {
143 cudaFree(s.ptr);
144 s.ptr = nullptr;
145 s.bytes = 0;
146 }
147 void* raw = nullptr;
148 if (cudaMalloc(&raw, bytes) != kCudaSuccess || raw == nullptr) {
149 return false;
150 }
151 s.ptr = static_cast<double*>(raw);
152 s.bytes = bytes;
153 return true;
154 }
155
156 bool symbols_loaded = false;
157 bool device_present = false;
158
159 template <typename Fn>
160 static Fn sym(void* handle, const char* name)
161 {
162 return reinterpret_cast<Fn>(dlsym(handle, name));
163 }
164
165 void load()
166 {
167 const bool verbose = g_cusolver_eigh_verbose;
168
169 // RTLD_LAZY (not RTLD_NOW): inside a host process that has already
170 // loaded another CUDA runtime (e.g. the metatomic/torch oracle's
171 // bundled libs), eager resolution of libcusolver against an
172 // incompatible pre-loaded libcublasLt/libcublas/libnvJitLink can make
173 // dlopen fail outright. Lazy binding defers symbol resolution to call
174 // time, and pre-loading the direct dependencies below (RTLD_GLOBAL)
175 // gives the loader the matching versions from the conda env first.
176 const int flags = RTLD_LAZY | RTLD_GLOBAL;
177 const char* deps[] = {"libnvJitLink.so.12",
178 "libnvJitLink.so",
179 "libcublas.so.12",
180 "libcublas.so",
181 "libcublasLt.so.12",
182 "libcublasLt.so",
183 nullptr};
184 for (int i = 0; deps[i] != nullptr; ++i)
185 dlopen(deps[i], flags);
186 // Re-dlopen whichever cublas is now resident purely to retain a
187 // handle for the dgemm symbols; the soname is already mapped, so
188 // this cannot change the load order above.
189 const char* cublas_libs[] = {"libcublas.so.12", "libcublas.so",
190 nullptr};
191 for (int i = 0; cublas_libs[i] != nullptr; ++i) {
192 cublas_handle_lib = dlopen(cublas_libs[i], flags);
193 if (cublas_handle_lib != nullptr) break;
194 }
195
196 const char* cudart_libs[] = {"libcudart.so", "libcudart.so.12",
197 "libcudart.so.11.0", "libcudart.so.11",
198 nullptr};
199 for (int i = 0; cudart_libs[i] != nullptr; ++i) {
200 cudart_handle = dlopen(cudart_libs[i], flags);
201 if (cudart_handle != nullptr) break;
202 }
203 const char* cusolver_libs[] = {"libcusolver.so", "libcusolver.so.11",
204 "libcusolver.so.12", nullptr};
205 for (int i = 0; cusolver_libs[i] != nullptr; ++i) {
206 cusolver_handle = dlopen(cusolver_libs[i], flags);
207 if (cusolver_handle != nullptr) break;
208 }
209 if (cudart_handle == nullptr || cusolver_handle == nullptr) {
210 if (verbose)
211 std::fprintf(stderr,
212 "[CusolverEigh] dlopen failed (cudart=%p "
213 "cusolver=%p): %s -> CPU fallback\n",
214 cudart_handle, cusolver_handle, dlerror());
215 return;
216 }
217
222 cudart_handle, "cudaDeviceSynchronize");
224 sym<cudaGetDeviceCount_t>(cudart_handle, "cudaGetDeviceCount");
226
228 sym<cusolverDnCreate_t>(cusolver_handle, "cusolverDnCreate");
230 sym<cusolverDnDestroy_t>(cusolver_handle, "cusolverDnDestroy");
232 cusolver_handle, "cusolverDnDsyevd_bufferSize");
234 sym<cusolverDnDsyevd_t>(cusolver_handle, "cusolverDnDsyevd");
235
236 if (cublas_handle_lib != nullptr) {
238 sym<cublasCreate_t>(cublas_handle_lib, "cublasCreate_v2");
240 sym<cublasDestroy_t>(cublas_handle_lib, "cublasDestroy_v2");
242 sym<cublasDgemm_t>(cublas_handle_lib, "cublasDgemm_v2");
244 sym<cublasDtrsm_t>(cublas_handle_lib, "cublasDtrsm_v2");
247 }
248
253 if (!symbols_loaded) {
254 if (verbose)
255 std::fprintf(stderr,
256 "[CusolverEigh] symbols_loaded=0 "
257 "(cudart=%p cusolver=%p) -> CPU fallback\n",
259 return;
260 }
261
262 int count = 0;
263 const cudaError_t cnt_rc = cudaGetDeviceCount(&count);
264 device_present = (cnt_rc == kCudaSuccess) && count > 0;
265 if (verbose)
266 std::fprintf(stderr,
267 "[CusolverEigh] symbols_loaded=1 "
268 "cudaGetDeviceCount rc=%d count=%d -> %s\n",
269 cnt_rc, count,
270 device_present ? "GPU path armed" : "CPU fallback");
271 }
272};
273
274CusolverEighLib::CusolverEighLib() : impl_(new Impl())
275{
276 impl_->load();
277}
278
279CusolverEighLib::~CusolverEighLib()
280{
281 delete impl_;
282}
283
285{
286 static CusolverEighLib lib;
287 return lib;
288}
289
290bool CusolverEighLib::available() const noexcept
291{
292 return impl_ != nullptr && impl_->symbols_loaded && impl_->device_present;
293}
294
295bool CusolverEighLib::allEigenpairs(const Eigen::MatrixXd& sym,
296 Eigen::VectorXd& evals,
297 Eigen::MatrixXd& evecs) const
298{
299 if (!available()) return false;
300 if (sym.rows() != sym.cols()) return false;
301 if (sym.rows() > static_cast<Eigen::Index>(std::numeric_limits<int>::max()))
302 return false;
303
304 const int n = static_cast<int>(sym.rows());
305 if (n == 0) {
306 evals.resize(0);
307 evecs.resize(0, 0);
308 return true;
309 }
310 // GPU dispatch floor: below this size the PCIe roundtrip dwarfs the
311 // O(n^3) work and the CPU dsyevd is faster outright, so tiny solves
312 // (the CuH2 dimer's n=14 covariances) never leave the host. This
313 // also keeps small-system runs off a layout-and-timing-sensitive
314 // crash in the dlopen'd cuSOLVER interop observed only when the
315 // device path engages at small n (bisect-confirmed unreachable-code
316 // trigger commit, valgrind-clean, CUDA_VISIBLE_DEVICES=""
317 // discriminates); the interop defect is tracked separately.
318 constexpr int kMinGpuEighN = 128;
319 if (n < kMinGpuEighN) return false;
320
321 Impl& d = *impl_;
322
323 // cusolverDnDsyevd overwrites A (column-major, lower triangle read) with
324 // the orthonormal eigenvectors as columns and fills W with ascending
325 // eigenvalues -- identical layout/order to Eigen SelfAdjointEigenSolver and
326 // LAPACK dsyevr range 'A'. EigenMatrix is ColMajor so the host buffer maps
327 // 1:1 onto the device column-major array.
328 Eigen::MatrixXd a = sym; // working copy, overwritten with eigenvectors
329 const std::size_t bytes_a = static_cast<std::size_t>(n) *
330 static_cast<std::size_t>(n) * sizeof(double);
331 const std::size_t bytes_w = static_cast<std::size_t>(n) * sizeof(double);
332
333 cusolverDnHandle_t handle = nullptr;
334 double* d_a = nullptr;
335 double* d_w = nullptr;
336 double* d_work = nullptr;
337 int* d_info = nullptr;
338 bool ok = false;
339
340 auto cleanup = [&]() {
341 // Scratch buffers are pooled and deliberately outlive the call;
342 // only the solver handle is per-call.
343 if (handle != nullptr) d.cusolverDnDestroy(handle);
344 };
345
346 // Per-step rc capture so a verbose run names the exact failing call (CUDA
347 // and cuSOLVER status codes share no enum, hence the labelled step).
348 const char* fail_step = nullptr;
349 int fail_rc = 0;
350 auto chk = [&](const char* step, int rc, int ok_code) -> bool {
351 if (rc == ok_code) return true;
352 fail_step = step;
353 fail_rc = rc;
354 return false;
355 };
356
357 do {
358 // A separate dlopen'd cudart runtime has no current device until one is
359 // set; without this the first cudaMalloc fails when the host process's
360 // CUDA context was created through a different runtime (torch's).
361 if (d.cudaSetDevice != nullptr &&
362 !chk("cudaSetDevice", d.cudaSetDevice(0), kCudaSuccess))
363 break;
364 if (!chk("cusolverDnCreate", d.cusolverDnCreate(&handle),
365 kCusolverStatusSuccess))
366 break;
367 if (!chk("reserve(A)", d.reserve(d.eig_a, bytes_a) ? 0 : 1, 0)) break;
368 if (!chk("reserve(W)", d.reserve(d.eig_w, bytes_w) ? 0 : 1, 0)) break;
369 if (!chk("reserve(info)", d.reserve(d.eig_info, sizeof(int)) ? 0 : 1,
370 0))
371 break;
372 d_a = d.eig_a.ptr;
373 d_w = d.eig_w.ptr;
374 d_info = reinterpret_cast<int*>(d.eig_info.ptr);
375 if (!chk("cudaMemcpy(A,HtoD)",
376 d.cudaMemcpy(d_a, a.data(), bytes_a, kCudaMemcpyHostToDevice),
377 kCudaSuccess))
378 break;
379
380 int lwork = 0;
381 if (!chk("syevd_bufferSize",
382 d.cusolverDnDsyevd_bufferSize(handle, kCusolverEigModeVector,
383 kCublasFillModeLower, n, d_a, n,
384 d_w, &lwork),
385 kCusolverStatusSuccess))
386 break;
387 if (lwork < 0) {
388 fail_step = "lwork<0";
389 fail_rc = lwork;
390 break;
391 }
392 if (!chk("reserve(work)",
393 d.reserve(d.eig_work,
394 static_cast<std::size_t>(lwork) * sizeof(double))
395 ? 0
396 : 1,
397 0))
398 break;
399 d_work = d.eig_work.ptr;
400
401 if (!chk("cusolverDnDsyevd",
402 d.cusolverDnDsyevd(handle, kCusolverEigModeVector,
403 kCublasFillModeLower, n, d_a, n, d_w,
404 d_work, lwork, d_info),
405 kCusolverStatusSuccess))
406 break;
407 if (!chk("cudaDeviceSynchronize", d.cudaDeviceSynchronize(),
408 kCudaSuccess))
409 break;
410
411 int info = 1;
412 if (!chk("cudaMemcpy(info,DtoH)",
413 d.cudaMemcpy(&info, d_info, sizeof(int),
414 kCudaMemcpyDeviceToHost),
415 kCudaSuccess))
416 break;
417 if (info != 0) { // syevd failed to converge
418 fail_step = "syevd_info";
419 fail_rc = info;
420 break;
421 }
422
423 evals.resize(n);
424 evecs.resize(n, n);
425 if (!chk("cudaMemcpy(W,DtoH)",
426 d.cudaMemcpy(evals.data(), d_w, bytes_w,
427 kCudaMemcpyDeviceToHost),
428 kCudaSuccess))
429 break;
430 if (!chk("cudaMemcpy(V,DtoH)",
431 d.cudaMemcpy(evecs.data(), d_a, bytes_a,
432 kCudaMemcpyDeviceToHost),
433 kCudaSuccess))
434 break;
435 ok = true;
436 } while (false);
437
438 // A GPU eigensolve failure silently degrading to the CPU path is a
439 // wall-time cliff worth surfacing, but gated behind the same verbose flag
440 // as the availability probes above: on a device where the dlopen'd cuSOLVER
441 // interop is unreliable (tracked-separately defect) it fires on EVERY
442 // eigensolve, which spams a production run and its captured stderr. The CPU
443 // fallback produces correct results either way; set verbose to trace it.
444 if (!ok && g_cusolver_eigh_verbose) {
445 std::fprintf(stderr,
446 "[CusolverEigh] GPU eigensolve FAILED at %s rc=%d (n=%d) "
447 "-> CPU fallback\n",
448 fail_step ? fail_step : "?", fail_rc, n);
449 }
450
451 // One-time confirmation that the GPU eigensolve actually ran. Printed
452 // unconditionally (once per process) so every GPU run -- campaign cell or
453 // validation -- self-documents that the dual-kernel eigensolve engaged the
454 // A100 rather than the CPU fallback, without depending on an env var being
455 // forwarded through mpirun.
456 if (ok) {
457 static bool announced = false;
458 if (!announced) {
459 announced = true;
460 std::fprintf(stderr,
461 "[CusolverEigh] cuSOLVER syevd active on GPU "
462 "(first solve n=%d)\n",
463 n);
464 }
465 }
466
467 cleanup();
468 return ok;
469}
470
471bool CusolverEighLib::gemmNN(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B,
472 Eigen::MatrixXd& C) const
473{
474 if (!available() || !impl_->cublas_symbols_loaded) return false;
475 if (A.cols() != B.rows()) return false;
476 const Eigen::Index m64 = A.rows();
477 const Eigen::Index k64 = A.cols();
478 const Eigen::Index n64 = B.cols();
479 constexpr Eigen::Index kIntMax =
480 static_cast<Eigen::Index>(std::numeric_limits<int>::max());
481 if (m64 > kIntMax || k64 > kIntMax || n64 > kIntMax) return false;
482 // Dispatch floor mirrors the eigensolve's: below it the PCIe roundtrip
483 // dwarfs the O(mnk) work and the host product wins outright.
484 constexpr int kMinGpuGemmDim = 128;
485 if (m64 < kMinGpuGemmDim || k64 < kMinGpuGemmDim || n64 < kMinGpuGemmDim)
486 return false;
487 const int m = static_cast<int>(m64);
488 const int k = static_cast<int>(k64);
489 const int n = static_cast<int>(n64);
490
491 Impl& d = *impl_;
492 const std::size_t bytes_a = static_cast<std::size_t>(m) *
493 static_cast<std::size_t>(k) * sizeof(double);
494 const std::size_t bytes_b = static_cast<std::size_t>(k) *
495 static_cast<std::size_t>(n) * sizeof(double);
496 const std::size_t bytes_c = static_cast<std::size_t>(m) *
497 static_cast<std::size_t>(n) * sizeof(double);
498
499 double* d_a = nullptr;
500 double* d_b = nullptr;
501 double* d_c = nullptr;
502 bool ok = false;
503
504 // Scratch is pooled across calls; nothing to release here.
505 auto cleanup = [] {};
506
507 const char* fail_step = nullptr;
508 int fail_rc = 0;
509 auto chk = [&](const char* step, int rc, int ok_code) -> bool {
510 if (rc == ok_code) return true;
511 fail_step = step;
512 fail_rc = rc;
513 return false;
514 };
515
516 do {
517 if (d.cudaSetDevice != nullptr &&
518 !chk("cudaSetDevice", d.cudaSetDevice(0), kCudaSuccess))
519 break;
520 if (d.cublas_ctx == nullptr) {
521 if (d.cublas_ctx_failed) break;
522 if (!chk("cublasCreate", d.cublasCreate(&d.cublas_ctx),
523 kCublasStatusSuccess)) {
524 d.cublas_ctx = nullptr;
525 d.cublas_ctx_failed = true;
526 break;
527 }
528 }
529 if (!chk("reserve(A)", d.reserve(d.gemm_a, bytes_a) ? 0 : 1, 0)) break;
530 if (!chk("reserve(B)", d.reserve(d.gemm_b, bytes_b) ? 0 : 1, 0)) break;
531 if (!chk("reserve(C)", d.reserve(d.gemm_c, bytes_c) ? 0 : 1, 0)) break;
532 d_a = d.gemm_a.ptr;
533 d_b = d.gemm_b.ptr;
534 d_c = d.gemm_c.ptr;
535 if (!chk("cudaMemcpy(A,HtoD)",
536 d.cudaMemcpy(d_a, A.data(), bytes_a, kCudaMemcpyHostToDevice),
537 kCudaSuccess))
538 break;
539 if (!chk("cudaMemcpy(B,HtoD)",
540 d.cudaMemcpy(d_b, B.data(), bytes_b, kCudaMemcpyHostToDevice),
541 kCudaSuccess))
542 break;
543
544 const double alpha = 1.0;
545 const double beta = 0.0;
546 if (!chk("cublasDgemm",
547 d.cublasDgemm(d.cublas_ctx, kCublasOpN, kCublasOpN, m, n, k,
548 &alpha, d_a, m, d_b, k, &beta, d_c, m),
549 kCublasStatusSuccess))
550 break;
551 if (!chk("cudaDeviceSynchronize", d.cudaDeviceSynchronize(),
552 kCudaSuccess))
553 break;
554
555 C.resize(m, n);
556 if (!chk("cudaMemcpy(C,DtoH)",
557 d.cudaMemcpy(C.data(), d_c, bytes_c, kCudaMemcpyDeviceToHost),
558 kCudaSuccess))
559 break;
560 ok = true;
561 } while (false);
562
563 if (!ok && fail_step != nullptr) {
564 std::fprintf(stderr,
565 "[CusolverEigh] GPU dgemm FAILED at %s rc=%d "
566 "(m=%d n=%d k=%d) -> CPU fallback\n",
567 fail_step, fail_rc, m, n, k);
568 }
569
570 cleanup();
571 return ok;
572}
573
575 const Eigen::MatrixXd& L,
576 Eigen::MatrixXd& B) const
577{
578 if (!available() || !impl_->cublas_symbols_loaded ||
579 impl_->cublasDtrsm == nullptr)
580 return false;
581 if (L.rows() != L.cols() || B.rows() != L.rows()) return false;
582 constexpr Eigen::Index kIntMax =
583 static_cast<Eigen::Index>(std::numeric_limits<int>::max());
584 if (L.rows() > kIntMax || B.cols() > kIntMax) return false;
585 // Below this order the solve is cheaper than the round trip.
586 constexpr Eigen::Index kMinGpuTrsmOrder = 512;
587 if (L.rows() < kMinGpuTrsmOrder || B.cols() == 0) return false;
588 const int n = static_cast<int>(L.rows());
589 const int m = static_cast<int>(B.cols());
590 Impl& d = *impl_;
591 const std::size_t bytes_l = static_cast<std::size_t>(n) *
592 static_cast<std::size_t>(n) * sizeof(double);
593 const std::size_t bytes_b = static_cast<std::size_t>(n) *
594 static_cast<std::size_t>(m) * sizeof(double);
595 bool ok = false;
596 const char* fail_step = nullptr;
597 int fail_rc = 0;
598 auto chk = [&](const char* step, int rc, int ok_code) -> bool {
599 if (rc == ok_code) return true;
600 fail_step = step;
601 fail_rc = rc;
602 return false;
603 };
604 do {
605 if (d.cudaSetDevice != nullptr &&
606 !chk("cudaSetDevice", d.cudaSetDevice(0), kCudaSuccess))
607 break;
608 if (d.cublas_ctx == nullptr) {
609 if (d.cublas_ctx_failed) break;
610 if (!chk("cublasCreate", d.cublasCreate(&d.cublas_ctx),
611 kCublasStatusSuccess)) {
612 d.cublas_ctx = nullptr;
613 d.cublas_ctx_failed = true;
614 break;
615 }
616 }
617 if (!(d.trsm_resident && d.trsm_epoch == epoch && d.trsm_n == n)) {
618 d.trsm_resident = false;
619 if (!chk("reserve(L)", d.reserve(d.trsm_l, bytes_l) ? 0 : 1, 0))
620 break;
621 if (!chk("cudaMemcpy(L,HtoD)",
622 d.cudaMemcpy(d.trsm_l.ptr, L.data(), bytes_l,
623 kCudaMemcpyHostToDevice),
624 kCudaSuccess))
625 break;
626 d.trsm_epoch = epoch;
627 d.trsm_n = n;
628 d.trsm_resident = true;
629 }
630 if (!chk("reserve(B)", d.reserve(d.trsm_b, bytes_b) ? 0 : 1, 0)) break;
631 if (!chk("cudaMemcpy(B,HtoD)",
632 d.cudaMemcpy(d.trsm_b.ptr, B.data(), bytes_b,
633 kCudaMemcpyHostToDevice),
634 kCudaSuccess))
635 break;
636 const double alpha = 1.0;
637 // cublasSideMode_t CUBLAS_SIDE_LEFT = 0, cublasFillMode_t
638 // CUBLAS_FILL_MODE_LOWER = 0, cublasOperation_t CUBLAS_OP_N = 0,
639 // cublasDiagType_t CUBLAS_DIAG_NON_UNIT = 0.
640 if (!chk("cublasDtrsm",
641 d.cublasDtrsm(d.cublas_ctx, 0, 0, 0, 0, n, m, &alpha,
642 d.trsm_l.ptr, n, d.trsm_b.ptr, n),
643 kCublasStatusSuccess))
644 break;
645 if (!chk("cudaDeviceSynchronize", d.cudaDeviceSynchronize(),
646 kCudaSuccess))
647 break;
648 if (!chk("cudaMemcpy(B,DtoH)",
649 d.cudaMemcpy(B.data(), d.trsm_b.ptr, bytes_b,
650 kCudaMemcpyDeviceToHost),
651 kCudaSuccess))
652 break;
653 ok = true;
654 } while (false);
655 if (!ok) {
656 d.trsm_resident = false;
657 if (fail_step != nullptr)
658 std::fprintf(stderr,
659 "[CusolverEigh] GPU dtrsm FAILED at %s rc=%d "
660 "(n=%d m=%d) -> CPU fallback\n",
661 fail_step, fail_rc, n, m);
662 }
663 return ok;
664}
665
666} // namespace linalg
667} // namespace gpr
void * cusolverDnHandle_t
void * cublasHandle_t
int cusolverStatus_t
int cublasStatus_t
Runtime-dlopen'd cuSOLVER dense symmetric eigensolver (syevd).
bool gemmNN(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B, Eigen::MatrixXd &C) const
static CusolverEighLib & instance()
bool allEigenpairs(const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs) const
bool available() const noexcept
bool trsmLowerResident(std::uint64_t epoch, const Eigen::MatrixXd &L, Eigen::MatrixXd &B) const
static void setVerbose(bool verbose) noexcept
uint64_t epoch
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
cudaGetDeviceCount_t cudaGetDeviceCount
cusolverDnDestroy_t cusolverDnDestroy
bool reserve(Scratch &s, std::size_t bytes)
cusolverDnDsyevd_bufferSize_t cusolverDnDsyevd_bufferSize
cudaDeviceSynchronize_t cudaDeviceSynchronize
static Fn sym(void *handle, const char *name)