What Is the CUDA Runtime API? A Practical Guide to Memory and Kernel Execution
The CUDA Runtime API is NVIDIA’s C/C++ interface for connecting device selection, memory management, and kernel execution in GPU programs. It wraps CUDA Driver API functionality in simpler calls and defaults, so applications do not have to manage contexts or kernel modules explicitly at every step. CPU and GPU memory still do not become one shared allocation, however, and a kernel launch normally returns without waiting for the GPU to finish; developers need to understand data movement, completion, and error boundaries.
What Is the CUDA Runtime API? A Practical Guide to Memory and Kernel Execution
The CUDA Runtime API is NVIDIA’s C/C++ interface for connecting device selection, memory management, and kernel execution in GPU programs. It wraps CUDA Driver API functionality in simpler calls and defaults, so applications do not have to manage contexts or kernel modules explicitly at every step. CPU and GPU memory still do not become one shared allocation, however, and a kernel launch normally returns without waiting for the GPU to finish; developers need to understand data movement, completion, and error boundaries.
What the CUDA Runtime API abstracts
A CUDA C++ program combines host code that runs on the CPU with kernels that execute in parallel on the GPU. Host code calls Runtime functions such as cudaMalloc, while a __global__ kernel is launched with CUDA C++ syntax such as transform<<<grid, block>>>(...). NVIDIA CUDA Toolkit’s nvcc is the compiler driver that builds host and device code together.
The Runtime API’s main benefit is simpler setup for recurring device work. In the common C++ path, it initializes the device’s primary context when needed and manages kernel code on the Runtime side. A program does not need to create a context, make it current on a thread, load a module from a file, and retrieve a function handle by hand for every ordinary launch. This abstraction reduces code and responsibility; it does not provide every control needed to switch modules dynamically or manage multiple contexts precisely.
| Area | CUDA Runtime API | CUDA Driver API |
|---|---|---|
| Main role | Concisely connects memory and execution calls in ordinary CUDA C++ applications | Explicitly controls device contexts, modules, and function handles |
| Execution setup | Commonly handles default context and module management implicitly | Makes a context current to a thread and prepares modules and kernels directly |
| Suitable when | An application does not require direct low-level control | Dynamic module loading, explicit context management, or Driver-only features are needed |
| Consideration | Account for shared-context lifetime and implicit defaults | More code; resource lifetime and thread context are managed directly |
The Runtime API is built on the Driver API, but this does not establish that one is always faster. Choose based on the control you need and the implementation cost. Also distinguish the benefit of the memory or kernel operation from the difference between interface layers.
How device selection and context lifetime fit together
Runtime functions use the CUDA Driver context that is current on the calling host thread. In an ordinary program that has not specified another context, the Runtime can select and initialize the device’s primary context when needed. Runtime-using components in a process may share that primary context. This is convenient for a simple application, but it means ownership matters in plugins and larger applications.
If several libraries or plugins do GPU work in one process, one component calling cudaDeviceReset() to deinitialize the shared primary context can affect the others. Do not use cudaDeviceReset() as routine cleanup after every task. It is generally safer to keep the context until the process exits and have a library release only the memory or streams it owns. If a separate context is truly needed, check the Runtime/Driver interoperability rules and choose a path that manages it explicitly.
Why CPU and GPU memory are handled separately
A host pointer refers to memory the CPU accesses; a device pointer returned by cudaMalloc refers to GPU-side memory. They refer to resources in distinct address spaces, so do not assume a CPU array can be passed directly to a kernel. cudaMemcpy crosses this boundary by taking a byte count and a copy direction. The common directions are host-to-device, device-to-host, device-to-device, and host-to-host.
For example, copy input array x to deviceX, let a kernel write results to deviceY, and copy those results back to host array y. Copy size is in bytes, not elements, so compute it as count * sizeof(float). Device memory returned by cudaMalloc is not automatically initialized to zero. If values must be initialized, copy them explicitly or use an appropriate initialization call.
Do not reduce copy functions with and without the Async suffix to “always asynchronous” versus “always synchronous.” Actual host waiting and copy completion depend on arguments such as transfer direction, page-locking, and stream. In particular, confirm that a device-to-host copy has completed before the host reads its result. Start with cudaMemcpy and explicit synchronization so the meaning is clear; study cudaMemcpyAsync, pinned host memory, and streams separately when overlap or bandwidth optimization is needed.
What does a kernel launch start?
A CUDA kernel is a device function defined so many GPU threads can apply the same code to different data. In the call syntax kernel<<<grid, block>>>(arguments), grid specifies the number of blocks and block specifies the number of threads in each block. For example, four blocks of 256 threads can cover an array of 1,024 elements; inside the kernel, each thread must check that its index is within the array bounds.
The code below applies 2*x[i]+1 to each input x[i] and stores it in y[i]. It is an illustrative CUDA C++ example of a common single-input workflow; it does not mean the code was compiled or run in this environment. The helper function check immediately inspects Runtime return values and exits the example process after printing an error string. A real library should return errors to its caller and design an error path that releases resources already acquired instead of terminating the process.
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
static void check(cudaError_t status, const char* operation) {
if (status != cudaSuccess) {
std::fprintf(stderr, "%s: %s\n", operation, cudaGetErrorString(status));
std::exit(EXIT_FAILURE);
}
}
__global__ void transform(const float* x, float* y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
y[i] = 2.0f * x[i] + 1.0f;
}
}
int main() {
constexpr int n = 1024;
constexpr int threads = 256;
constexpr size_t bytes = n * sizeof(float);
float x[n];
float y[n];
float* deviceX = nullptr;
float* deviceY = nullptr;
for (int i = 0; i < n; ++i) {
x[i] = static_cast<float>(i);
}
check(cudaSetDevice(0), "cudaSetDevice");
check(cudaMalloc(reinterpret_cast<void**>(&deviceX), bytes), "cudaMalloc deviceX");
check(cudaMalloc(reinterpret_cast<void**>(&deviceY), bytes), "cudaMalloc deviceY");
check(cudaMemcpy(deviceX, x, bytes, cudaMemcpyHostToDevice), "copy input");
transform<<<(n + threads - 1) / threads, threads>>>(deviceX, deviceY, n);
check(cudaGetLastError(), "launch transform");
check(cudaDeviceSynchronize(), "wait for transform");
check(cudaMemcpy(y, deviceY, bytes, cudaMemcpyDeviceToHost), "copy output");
check(cudaFree(deviceY), "free deviceY");
check(cudaFree(deviceX), "free deviceX");
std::printf("y[0]=%.1f, y[%d]=%.1f\n", y[0], n - 1, y[n - 1]);
return 0;
}The example fixes the input length at 1,024, so four blocks of 256 threads cover every element. For a general length, compute the number of blocks with ceiling division and check i < n in each thread so excess threads in the final block do not access outside the array. In real work, also check that the selected GPU supports the chosen block size.
How do you confirm completion and check errors?
A kernel launch submits work to the GPU and normally returns to the host thread immediately. The fact that the next CPU line has run does not mean the GPU has finished. In the example, cudaDeviceSynchronize() makes the host wait until previously submitted GPU work is complete, giving a simple boundary for checking that the result is ready. This call can also wait for work submitted to multiple device streams; a larger application may prefer a narrower stream or event wait.
Check each cudaError_t return. Immediately after a <<<...>>> launch, use cudaGetLastError() or, depending on the intent, cudaPeekAtLastError() to inspect errors that are already visible, such as invalid launch configuration. The launch syntax itself does not return a cudaError_t. Getting cudaSuccess immediately after launch does not prove that the kernel body completed successfully. Asynchronous execution errors, such as an invalid memory access, may appear at a later error query or synchronization call, so also inspect the return value at the completion boundary. cudaGetLastError() reads and clears the last error state for the calling host thread and that Runtime library instance; cudaPeekAtLastError() does not clear it.
When an error occurs, first inspect the failing call and the data boundary. For cudaErrorInvalidValue or a bad copy direction, check arguments, sizes, and pointer types. For cudaErrorMemoryAllocation, review device allocations that are still live and their cleanup paths. If a kernel execution error appears at synchronization, trace index bounds, pointer allocation and lifetime, and kernel arguments. Do not assume an output buffer is valid after a failure or retry unconditionally with cudaDeviceReset(). In particular, recovery in a program with a shared context depends on the error type and resource ownership.
A basic procedure is:
Confirm that the CUDA Toolkit and NVIDIA driver are installed in a supported environment and that `nvcc` can build a `.cu` file; if useful, check the result of `cudaGetDeviceCount`.
Select a device with `cudaSetDevice`, compute allocation sizes in bytes, and allocate only the device memory the work needs.
Copy the input with the `cudaMemcpyHostToDevice` direction and check each Runtime call’s return value immediately.
Choose grid and block dimensions, launch the kernel, check the launch error, and wait for completion with error checking where the host needs the result.
Retrieve the result with `cudaMemcpyDeviceToHost`, compare it with an expected value, and release device memory owned by both success and failure paths.
A small example can be compiled with a command such as nvcc -o runtime_demo runtime_demo.cu. Successful compilation alone does not prove that GPU execution succeeded, so separately check the result and CUDA error returns on an actual device.
When should you choose the Runtime API or the Driver API?
For most CUDA C++ applications that do not need direct context or module control, the Runtime API is a sensible starting point. It connects allocation, copy, kernel launch, and result checking in a short workflow while still letting the program make errors and data lifetime explicit. Driver API control is useful when modules must be selected and loaded dynamically, a Driver-only feature is required, or context ownership must be managed directly for each thread.
The two APIs can be used in one process, but that does not mean their context and resource-lifetime rules can be mixed freely. Runtime calls use the calling thread’s current Driver context; when there is no such context, the Runtime can initialize and use a primary context. Check which context allocated memory, which API family will release it, and whether other process components share the context. Do not assume a speedup merely because a lower-level interface is used; choose by required control and implementation cost.
References
[CUDA Programming Guide: Intro to CUDA C++](https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/intro-to-cuda-cpp.html)
[CUDA Runtime API Reference: Memory Management](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html)
[CUDA Runtime API Reference: API Synchronization Behavior](https://docs.nvidia.com/cuda/cuda-runtime-api/api-sync-behavior.html)
[CUDA Runtime API Reference: Difference Between the Driver and Runtime APIs](https://docs.nvidia.com/cuda/cuda-runtime-api/driver-vs-runtime-api.html)
[CUDA Runtime API Reference: Error Handling](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__ERROR.html)