The CUDA backend: NVIDIA GPUs
MTL5 runs dense float and double products, LU and Cholesky factorizations, and their solves on NVIDIA GPUs through cuBLAS and cuSOLVER. It is the second backend on the accelerator core, after Metal, and follows the accelerator backend architecture. Tracked in issue 1018, under the umbrella #225.
Enabling it
Section titled “Enabling it”cmake -B build -DMTL5_WITH_CUDA=ON # finds the CUDA toolkitcmake -B build -DMTL5_WITH_CUDA=ON -DCUDAToolkit_ROOT=/usr/local/cuda-12.9The backend is header-only C++ over the C APIs of the CUDA runtime, cuBLAS and cuSOLVER, so the host compiler builds it: nvcc is not involved, and no MTL5 code is compiled for the GPU. MTL5::cuda is an interface target that links CUDA::cudart, CUDA::cublas and CUDA::cusolver and defines MTL5_HAS_CUDA. Code built without it is unchanged.
target_link_libraries(my_app PRIVATE MTL5::cuda)An installed MTL5 built with the option exports MTL5::cuda, and its package configuration finds the CUDA toolkit for the consumer.
Memory
Section titled “Memory”runtime::cuda names memory by pointers. CUDA’s unified virtual addressing makes every pointer unique across the host and the devices, so one cudaMemcpy copies in any direction.
| Space | CUDA allocation | Host access |
|---|---|---|
memory_space::device<runtime::cuda> | cudaMalloc | none: only the GPU touches it |
memory_space::shared<runtime::cuda> | cudaMallocManaged | yes |
memory_space::pinned<runtime::cuda> | cudaMallocHost | yes: page-locked host memory |
Every kind allocates zero-filled memory. Since device memory cannot run a constructor, it holds only element types whose value is all-zero bytes: arithmetic types, enumerations, pointers and floating-point std::complex. A program opts another such type in by specializing mtl::zero_fill_is_value_init (include/mtl/memory/zero_fill.hpp). Shared memory is the natural space on an integrated GPU such as the Jetson, which shares the CPU’s physical memory; on a discrete card the driver migrates its pages. Where runtime::cuda::concurrent_managed_access() is false (Windows, WSL and some Tegra devices), the host must not touch shared memory while a kernel may be running. MTL5’s calls wait for the device before they return, but GPU work started by another thread is not covered. Pinned memory is host memory that copies quickly; operations on it run on the host.
#include <mtl/mtl.hpp>#include <mtl/interface/cuda.hpp>
using dev = mtl::memory_space::device<mtl::runtime::cuda>; // or device<> in a CUDA buildmtl::mat::dense2D<double> A = ..., B = ...;auto dA = mtl::copy_to<dev>(A);auto dB = mtl::copy_to<dev>(B);auto dC = mtl::copy_to<dev>(mtl::mat::dense2D<double>(A.num_rows(), B.num_cols()));mtl::mult(dA, dB, dC); // cublasDgemmstd::vector<std::size_t> pivot;mtl::lu_factor(dA, pivot); // cusolverDnDgetrfauto C = mtl::to_host(dC);Operations
Section titled “Operations”| Call | Operands | Runs as |
|---|---|---|
mult(A, B, C) | dense2D, all in CUDA memory | cublas<t>gemm |
mult(A, x, y) | dense2D and dense_vector, all in CUDA memory | cublas<t>gemv |
lu_factor(A, pivot) | dense2D in CUDA memory | cusolverDn<t>getrf |
lu_solve(LU, pivot, x, b) | the factor and dense_vectors, all in CUDA memory | cusolverDn<t>getrs |
cholesky_factor(A) | dense2D in CUDA memory | cusolverDn<t>potrf |
cholesky_solve(L, x, b) | the factor and dense_vectors, all in CUDA memory | cusolverDn<t>potrs |
floatanddouble, one value type across the operands of a call. Other element types, and custom number types, take the host routines in shared memory and do not compile in device memory. A non-defaultAccumulator(#585) never reaches the GPU either.- Placement follows the operands. Every operand in CUDA device or shared memory, mixed freely, runs on the GPU. A pinned operand keeps the call off the GPU: with shared and pinned operands it runs on the host, and with a device-memory operand it does not compile, since the host cannot read that operand. Copy it to device or shared memory first. The dispatch trace counts
gemm_cuda,gemv_cuda,getrf_cuda,getrs_cuda,potrf_cudaandpotrs_cuda. - Orientation is free. cuBLAS and cuSOLVER read column-major storage, so a row-major matrix is its stored transpose. Products pass the transpose flags that give the right result, and a row-major
Cis computed asC^T = B^T A^T. A row-major LU is transposed into column-major scratch (cublas<t>geam) and back, as is the factor in each row-major solve. A row-major Cholesky needs no transpose: its stored transpose is the same symmetric matrix, whose upper factorL^Tlies exactly whereLlies. - Synchronous. Each call waits for the device, as phase 1 of the design promises, and reports a CUDA, cuBLAS or cuSOLVER error as
std::runtime_error. Each thread has its own cuBLAS and cuSOLVER handles, one pair for each device it uses (cudaSetDevicepicks the device). Operands live on the current device (cudaSetDevicepicks it): phase 1 does not move work between GPUs, and an operand allocated on another device is not detected. Streams come later. - Aliasing. A product whose result shares memory with an operand goes through a temporary. A solve may take
xandbas the same vector, and solves in place; anxthat overlaps part ofb, or the factor, goes through a temporary.
Factorizations
Section titled “Factorizations”The factorizations return what the host routines return, and leave the same factor in A, as on Metal:
- Pivots are the host’s convention: row
iwas interchanged with rowpivot[i], 0-based. cuSOLVER’s 1-based pivots are converted, so a factor from the GPU solves on the host, and the reverse. - Failures are the host’s. cuSOLVER reports the first zero pivot, but a blocked factorization leaves a different partial factor from the host’s, and a NaN pivot is not reported. The backend saves a device copy of
A, factors in place, and tests the factor’s diagonal as the host does (zero or NaN for LU, not positive for Cholesky). On a failure the host routine factors the copy instead, so the return code and the contents ofAmatch the host exactly. The shared mechanism isinclude/mtl/interface/device_fallback.hpp. - The other triangle of a Cholesky factor is left as it was, as cuSOLVER and the host routine both leave it.
- Size. cuBLAS and cuSOLVER take dimensions as
int, so a larger matrix throwsstd::length_error. A non-square matrix in device memory throwsstd::invalid_argument; one in shared memory first meets the host routine’s assertion, as a host matrix does. The solves check the factor’s shape themselves, in every build.
Precision
Section titled “Precision”Every CUDA GPU has FP64, but consumer and embedded parts (the Jetson’s Orin among them) run it at a small fraction of FP32. double operands run on the GPU anyway; a benchmark should state which precision it ran in.
Testing
Section titled “Testing”tests/unit/cuda/ checks the allocations, the copies, every orientation of mult, and LU and Cholesky (factors, pivots, solves, failures and edges) against MTL5’s host routines, in float and double. A test skips itself on a machine without a CUDA device, and fails instead when MTL5_REQUIRE_CUDA is set.
GitHub’s hosted runners have no NVIDIA GPU. CI’s Linux x64 CUDA lane installs the toolkit, builds the tests with the host compiler and runs them, so each one compiles, links and loads, then skips. The GPU runs happen on a machine with an NVIDIA GPU:
cmake -B build -DMTL5_WITH_CUDA=ONcmake --build build --target cuda_test_cudaMTL5_REQUIRE_CUDA=1 ctest --test-dir build -R '^cuda_' --output-on-failureA self-hosted runner on such a machine (a cloud GPU instance or the Jetson) would turn the lane into a GPU lane by setting MTL5_REQUIRE_CUDA.
Not done yet
Section titled “Not done yet”- A GPU run. The tests have run against a host emulation of the CUDA APIs and in CI to the skip, not yet on an NVIDIA GPU.
- Eigenvalues and the SVD through cuSOLVER (
syevd,gesvd), and complex element types. - Streams (
stream<runtime::cuda>), several right-hand sides per solve, and cuSPARSE for sparse matrices.