What Is cuBLAS? Calling GPU Linear Algebra Routines from CUDA C++
cuBLAS is NVIDIA’s library for running standard BLAS vector and matrix operations on a GPU from a CUDA application. Instead of writing a CUDA kernel for every operation, you can call a routine that matches the calculation. Your program still has to provide GPU-accessible input and output buffers, correct sizes and strides, and a valid library handle. This guide covers the standard cuBLAS API from CUDA C++.
What Is cuBLAS? Calling GPU Linear Algebra Routines from CUDA C++
cuBLAS is NVIDIA’s library for running standard BLAS vector and matrix operations on a GPU from a CUDA application. Instead of writing a CUDA kernel for every operation, you can call a routine that matches the calculation. Your program still has to provide GPU-accessible input and output buffers, correct sizes and strides, and a valid library handle. This guide covers the standard cuBLAS API from CUDA C++.
What work does cuBLAS do?
BLAS (Basic Linear Algebra Subprograms) provides common building blocks for vector and matrix calculations. Level 1 routines operate on scalars and vectors; Level 2 routines combine a matrix and a vector; Level 3 routines combine matrices. cuBLAS implements these BLAS operations for NVIDIA GPUs on top of the CUDA Runtime. See the Netlib BLAS overview and NVIDIA cuBLAS documentation.
| BLAS level | Input shape | Example operation | Example use |
|---|---|---|---|
| Level 1 | Vectors and scalars | SAXPY: y = αx + y | Scale a vector and accumulate it into another |
| Level 2 | A matrix and a vector | GEMV: y = αAx + βy | Multiply one matrix by a vector |
| Level 3 | Matrices | GEMM: C = αAB + βC | Multiply matrices and accumulate into the result |
With the standard cuBLAS API, the application prepares vectors and matrices in memory the GPU can access, calls the desired library routines, and copies results back to the host when needed. A routine does not automatically turn an ordinary host array into GPU memory. For matrix multiplication that needs more flexible layout, data type, or algorithm controls, consider the separate cuBLASLt API. cuBLASXt is another distinct API for dispatching work and data across host memory and one or more GPUs.
Why create a handle, and when should it be destroyed?
The current cuBLAS API uses the cublas_v2.h header. Create a cublasHandle_t with cublasCreate() and pass that handle to each cuBLAS routine. The handle holds library context and is tied to the current CUDA device and context. When using multiple GPUs, select the intended device before creating its handle, and keep that device and context valid while using the handle.
Call cublasDestroy() when the handle is no longer needed. Creating and destroying handles sets up and releases internal resources, so reuse a handle for an appropriate period of work instead of creating one for every operation. The library is thread-safe, but changing a shared handle’s configuration or destroying it can affect calls from other threads. NVIDIA recommends one handle per thread when multiple threads use the same GPU.
Use the cublas_v2.h API in new programs. The legacy API based on cublas.h is deprecated, and the two headers cannot be included together in one translation unit. Also check the cublasStatus_t returned by cuBLAS calls. It can identify call-level problems, including an uninitialized handle or invalid arguments.
How should GPU memory and array layout match?
Vector and matrix pointers passed to standard cuBLAS routines must refer to memory the GPU can access. A common workflow is to prepare input on the host, allocate device buffers with CUDA Runtime functions such as cudaMalloc(), and copy the input with a call such as cudaMemcpy(). Copy the result from the device to the host when the application needs it. Keep each buffer alive until GPU work has finished using it. The CUDA Runtime memory management reference documents allocation and copy functions.
For matrices, the physical storage order must match the arguments you pass. cuBLAS uses column-major storage for compatibility with Fortran. A C or C++ row-major array passed as if it were column-major can be accepted while representing a different matrix than you intended. For a column-major matrix, lda (the leading dimension) is the element spacing between the starts of columns. It is not always the logical number of columns. When passing a submatrix, use the actual allocated row count or physical stride.
Vector routines also accept increments such as incx and incy, which specify the spacing between consecutive elements. Use 1 for contiguous vectors. Use the actual element spacing for a strided vector, such as a row inside a column-major matrix. Increments count elements, not bytes. A wrong increment or leading dimension can access invalid memory or select unintended elements, so check the routine’s dimensions against the actual buffer layout.
How does SAXPY change its inputs?
The Level 1 routine cublasSaxpy() multiplies a single-precision vector x by a scalar α, adds the result to vector y, and writes the result back into y: yᵢ ← αxᵢ + yᵢ. Thus y is both an input and an output; its previous values are read. The snippet below shows only the call. It assumes d_x and d_y are already allocated on the device and that the default host scalar pointer mode is in effect.
float alpha = 2.0f; // host scalar in the default pointer mode
int n = 3;
cublasStatus_t status = cublasSaxpy(
handle, n, &alpha, d_x, 1, d_y, 1);
if (status != CUBLAS_STATUS_SUCCESS) {
// Record the error and take a safe cleanup path
}For example, if x = [1, 2, 3], the initial y = [10, 20, 30], and α = 2, the calculation produces [12, 24, 36]. This is an arithmetic example, not a result from running on a particular GPU or measuring performance. d_x and d_y are device pointers; increments of 1 mean both vectors are contiguous. Do not dereference device pointers on the CPU. To inspect values, copy the result into a host buffer or validate it on the GPU.
In what order should a first call be assembled?
Separate memory and handle setup, the calculation, and result inspection. Assume the host arrays x and y will be used to compute y = 2x + y.
Confirm that the installed CUDA Toolkit provides the compiler, cuBLAS header, and library, and that the NVIDIA GPU and driver fit the intended environment. The build must link both the CUDA Runtime and cuBLAS.
Select the GPU and call `cublasCreate()`. Because the handle is tied to the current device and CUDA context, select a different device and create a separate handle when needed.
Allocate device buffers for `x` and `y`, then copy the host values to them. Copy the initial values of `y` too, because SAXPY adds to the existing vector. Check that `n` agrees with the buffer lengths.
Call `cublasSaxpy(handle, n, &alpha, d_x, 1, d_y, 1)` and check that `cublasStatus_t` reports success. On failure, inspect arguments such as dimensions, pointers, and handle, then handle the error appropriately.
Confirm that the work is complete before reading the result. Copy `d_y` to the host and check each element against `2*x[i]+y_old[i]`. After validation, free the buffers and destroy the handle once.
The success status in step 4 describes the library call; it is different from confirming that the GPU calculation has finished and the CPU can safely read the result. GPU work submitted to the same stream is ordered, but the CPU needs a completion boundary before inspecting output. The CUDA API synchronization guide explains that even copy calls can behave differently from the host or device perspective depending on their arguments and memory types. In this example, synchronize the relevant stream or validate after a copy whose completion has been confirmed.
When should you use cuBLAS, and what should you check?
When a BLAS routine expresses the calculation and its data type and layout requirements fit, cuBLAS lets you use a standard GPU operation without writing that kernel yourself. It is useful when inputs already reside on the GPU for multiple calculations or when the application’s data flow matters more than implementing a kernel. A custom kernel may be needed when several operations must be fused into one pass or when BLAS does not express the computation. For matrix multiplication, consider cuBLASLt when you need its more flexible configuration. There is no universal rule that one option is always faster.
To assess performance or numerical results, do not compare routine names in isolation. Record whether input copies are included, the data type and compute precision, matching matrix layouts and sizes, and how setup costs are handled for repeated runs. With little computation, calls and data transfers can account for a substantial share of total time. Validate numerical output with a tolerance appropriate to the data type and accumulation method, and compare against an independent reference calculation when needed. These are experiment-design considerations, not measured performance results.
References
[NVIDIA cuBLAS 13.5 API Reference](https://docs.nvidia.com/cuda/cublas/)
[Netlib BLAS overview](https://www.netlib.org/blas/)
[CUDA Runtime API: Memory Management](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html)
[CUDA Runtime API: API Synchronization Behavior](https://docs.nvidia.com/cuda/cuda-runtime-api/api-sync-behavior.html)
[CUDA Programming Guide: Intro to CUDA C++](https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/intro-to-cuda-cpp.html)