Skip to content

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.

Terminal window
cmake -B build -DMTL5_WITH_CUDA=ON # finds the CUDA toolkit
cmake -B build -DMTL5_WITH_CUDA=ON -DCUDAToolkit_ROOT=/usr/local/cuda-12.9

The 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.

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.

SpaceCUDA allocationHost access
memory_space::device<runtime::cuda>cudaMallocnone: only the GPU touches it
memory_space::shared<runtime::cuda>cudaMallocManagedyes
memory_space::pinned<runtime::cuda>cudaMallocHostyes: 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 build
mtl::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); // cublasDgemm
std::vector<std::size_t> pivot;
mtl::lu_factor(dA, pivot); // cusolverDnDgetrf
auto C = mtl::to_host(dC);
CallOperandsRuns as
mult(A, B, C)dense2D, all in CUDA memorycublas<t>gemm
mult(A, x, y)dense2D and dense_vector, all in CUDA memorycublas<t>gemv
lu_factor(A, pivot)dense2D in CUDA memorycusolverDn<t>getrf
lu_solve(LU, pivot, x, b)the factor and dense_vectors, all in CUDA memorycusolverDn<t>getrs
cholesky_factor(A)dense2D in CUDA memorycusolverDn<t>potrf
cholesky_solve(L, x, b)the factor and dense_vectors, all in CUDA memorycusolverDn<t>potrs
  • float and double, 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-default Accumulator (#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_cuda and potrs_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 C is computed as C^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 factor L^T lies exactly where L lies.
  • 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 (cudaSetDevice picks the device). Operands live on the current device (cudaSetDevice picks 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 x and b as the same vector, and solves in place; an x that overlaps part of b, or the factor, goes through a temporary.

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 i was interchanged with row pivot[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 of A match the host exactly. The shared mechanism is include/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 throws std::length_error. A non-square matrix in device memory throws std::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.

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.

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:

Terminal window
cmake -B build -DMTL5_WITH_CUDA=ON
cmake --build build --target cuda_test_cuda
MTL5_REQUIRE_CUDA=1 ctest --test-dir build -R '^cuda_' --output-on-failure

A 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.

  • 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.