Loading...
Searching...
No Matches
gpr::linalg::CusolverEighLib Class Reference

#include <gpr/linalg/CusolverEigh.h>

Classes

struct  Impl

Public Member Functions

bool available () const noexcept
bool allEigenpairs (const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs) const
bool gemmNN (const Eigen::MatrixXd &A, const Eigen::MatrixXd &B, Eigen::MatrixXd &C) const
bool trsmLowerResident (std::uint64_t epoch, const Eigen::MatrixXd &L, Eigen::MatrixXd &B) const

Static Public Member Functions

static CusolverEighLib & instance ()
static void setVerbose (bool verbose) noexcept

Detailed Description

Definition at line 39 of file CusolverEigh.h.

Member Function Documentation

◆ allEigenpairs()

bool gpr::linalg::CusolverEighLib::allEigenpairs ( const Eigen::MatrixXd & sym,
Eigen::VectorXd & evals,
Eigen::MatrixXd & evecs ) const
nodiscard

Full symmetric eigendecomposition via cusolverDnDsyevd.

On success evals holds all eigenvalues in ASCENDING order and evecs the corresponding orthonormal eigenvectors as columns (matching Eigen::SelfAdjointEigenSolver and LAPACK dsyevr range 'A'). sym must be square; only its lower triangle is read. Returns false on any device/solver error (the caller falls back to the CPU path).

Definition at line 295 of file CusolverEigh.cpp.

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}
void * cusolverDnHandle_t
bool available() const noexcept

◆ available()

bool gpr::linalg::CusolverEighLib::available ( ) const
nodiscardnoexcept

True if the cuSOLVER + cudart symbols loaded and a CUDA device is usable. When false, allEigenpairs() always returns false.

Definition at line 290 of file CusolverEigh.cpp.

291{
292 return impl_ != nullptr && impl_->symbols_loaded && impl_->device_present;
293}

◆ gemmNN()

bool gpr::linalg::CusolverEighLib::gemmNN ( const Eigen::MatrixXd & A,
const Eigen::MatrixXd & B,
Eigen::MatrixXd & C ) const
nodiscard

C = A * B via cublasDgemm. Column-major end to end, no transposes. Returns false below the dispatch floor or on any device error (the caller falls back to the Eigen product).

Definition at line 471 of file CusolverEigh.cpp.

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}

◆ instance()

CusolverEighLib & gpr::linalg::CusolverEighLib::instance ( )
static

Definition at line 284 of file CusolverEigh.cpp.

285{
286 static CusolverEighLib lib;
287 return lib;
288}

◆ setVerbose()

void gpr::linalg::CusolverEighLib::setVerbose ( bool verbose)
staticnoexcept

Loader/step chatter on stderr. Wired from the GP report_level (>= 3); failures print regardless of this flag. Set before the first available()/allEigenpairs() call to cover dlopen loading.

Definition at line 81 of file CusolverEigh.cpp.

82{
83 g_cusolver_eigh_verbose = verbose;
84}

◆ trsmLowerResident()

bool gpr::linalg::CusolverEighLib::trsmLowerResident ( std::uint64_t epoch,
const Eigen::MatrixXd & L,
Eigen::MatrixXd & B ) const
nodiscard

Solve L X = B in place for a lower-triangular L that stays on the device between calls: the factor is uploaded when epoch or its order changes and reused otherwise, so a run of posterior variance queries against one training factor pays the upload once. Returns false below the dispatch floor or on any device error (the caller falls back to the Eigen triangular solve; B is then untouched).

Definition at line 574 of file CusolverEigh.cpp.

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}
uint64_t epoch

The documentation for this class was generated from the following files: