CUDA Streams and Concurrency
Chapter 6 — overlapping copies and kernels, events, and CUDA Graphs
What you will learn
- What a stream is, and what the default stream really synchronizes with
- How to overlap host-device copies with kernels, measured against a serial baseline
- Events for timing and for dependencies between streams
- Which API calls silently synchronize
- CUDA Graphs: cutting launch overhead for many small kernels
Chapter 3 measured that copying data over PCIe can take far longer than the kernel that uses it. The GPU has separate copy engines next to its SMs, so copies and kernels can run at the same time, but only if you tell CUDA which operations are independent. Streams are how you say that.
What a stream is
A stream is a queue of GPU work: copies, kernels, memsets, event records. Two rules define it:
- Operations in the same stream run in issue order. Each starts after the previous one finishes.
- Operations in different streams have no ordering. The GPU may run them at the same time, if it has free resources.
cudaStream_t s; cudaStreamCreate(&s); cudaMemcpyAsync(d_in, h_in, bytes, cudaMemcpyHostToDevice, s); // all three queue into s kernel<<<grid, block, 0, s>>>(d_in, d_out); // 4th launch parameter = stream cudaMemcpyAsync(h_out, d_out, bytes, cudaMemcpyDeviceToHost, s); // ...the CPU is free to do other work here... cudaStreamSynchronize(s); // wait for everything queued in s cudaStreamDestroy(s);
The default stream
Work issued without a stream goes to the default stream (stream 0). Two points are often stated wrongly:
- It is not synchronous with the host. A kernel launch into the default stream returns immediately, like any other launch. What blocks the host is
cudaMemcpy(the non-Async version), which returns only when the copy is done, and explicit synchronize calls. - It synchronizes with other streams. The legacy default stream waits for all work in other blocking streams before it starts, and they wait for it. One stray launch without a stream argument can therefore serialize a carefully overlapped program. Avoid it by creating streams with
cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), or by compiling withnvcc --default-stream per-thread, which gives each host thread an ordinary default stream.
Asynchronous copies need pinned memory
cudaMemcpyAsync only overlaps with other work when the host buffer is pinned (page-locked, allocated with cudaMallocHost or registered with cudaHostRegister). The copy engine reads pinned memory directly. With ordinary pageable memory the driver first copies the data into a pinned staging buffer, and the call behaves almost like a synchronous copy. Pin only the buffers you transfer: pinned memory cannot be swapped out, and pinning gigabytes can starve the operating system.
Overlapping copies and compute
The pattern: split the data into chunks and give each chunk its own sequence of copy-in, kernel and copy-out, spread over a few streams. While chunk 2 is being computed, chunk 3 is copied in and chunk 1 copied out.
The program below measures this. The kernel does enough arithmetic per element to take about as long as a copy, which is when overlap helps most. It runs the serial version first, then the pipelined one, and checks both against the CPU.
#include <cstdio> #include <cstdlib> #include <cmath> #include <chrono> #define CUDA_CHECK(call) \ do { \ cudaError_t err_ = (call); \ if (err_ != cudaSuccess) { \ fprintf(stderr, "CUDA error %s at %s:%d\n", \ cudaGetErrorString(err_), __FILE__, __LINE__); \ exit(1); \ } \ } while (0) #define ITERS 4000 __host__ __device__ float work(float x) { for (int k = 0; k < ITERS; k++) x = fmaf(x, 0.999f, 0.001f); return x; } __global__ void compute(const float *in, float *out, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) out[i] = work(in[i]); } double nowMs() { using namespace std::chrono; return duration<double, std::milli>(steady_clock::now().time_since_epoch()).count(); } const int n = 1 << 24, chunks = 16, nStreams = 4; const int chunkN = n / chunks; const size_t bytes = n * sizeof(float), chunkBytes = chunkN * sizeof(float); void copyIn(float *d, const float *h, int c, cudaStream_t s) { CUDA_CHECK(cudaMemcpyAsync(d + (size_t)c * chunkN, h + (size_t)c * chunkN, chunkBytes, cudaMemcpyHostToDevice, s)); } void copyOut(float *h, const float *d, int c, cudaStream_t s) { CUDA_CHECK(cudaMemcpyAsync(h + (size_t)c * chunkN, d + (size_t)c * chunkN, chunkBytes, cudaMemcpyDeviceToHost, s)); } void launch(const float *d_in, float *d_out, int c, cudaStream_t s) { size_t off = (size_t)c * chunkN; compute<<<(chunkN + 255) / 256, 256, 0, s>>>(d_in + off, d_out + off, chunkN); } int main() { float *h_in, *h_out, *d_in, *d_out; CUDA_CHECK(cudaMallocHost(&h_in, bytes)); // pinned: required for overlap CUDA_CHECK(cudaMallocHost(&h_out, bytes)); CUDA_CHECK(cudaMalloc(&d_in, bytes)); CUDA_CHECK(cudaMalloc(&d_out, bytes)); for (int i = 0; i < n; i++) h_in[i] = (i % 1000) * 0.001f; cudaStream_t s[nStreams]; for (int k = 0; k < nStreams; k++) CUDA_CHECK(cudaStreamCreateWithFlags(&s[k], cudaStreamNonBlocking)); int engines; CUDA_CHECK(cudaDeviceGetAttribute(&engines, cudaDevAttrAsyncEngineCount, 0)); printf("copy engines on this GPU: %d\n", engines); compute<<<1, 32>>>(d_in, d_out, 32); // warm-up CUDA_CHECK(cudaDeviceSynchronize()); const char *names[] = {"serial", "depth-first", "breadth-first"}; bool ok = true; for (int version = 0; version < 3; version++) { for (int i = 0; i < n; i++) h_out[i] = -1.0f; double t0 = nowMs(); if (version == 0) { // Serial: whole array in, whole kernel, whole array out, in one stream. Events time each stage. cudaEvent_t e[4]; for (int k = 0; k < 4; k++) CUDA_CHECK(cudaEventCreate(&e[k])); CUDA_CHECK(cudaEventRecord(e[0], s[0])); CUDA_CHECK(cudaMemcpyAsync(d_in, h_in, bytes, cudaMemcpyHostToDevice, s[0])); CUDA_CHECK(cudaEventRecord(e[1], s[0])); compute<<<(n + 255) / 256, 256, 0, s[0]>>>(d_in, d_out, n); CUDA_CHECK(cudaEventRecord(e[2], s[0])); CUDA_CHECK(cudaMemcpyAsync(h_out, d_out, bytes, cudaMemcpyDeviceToHost, s[0])); CUDA_CHECK(cudaEventRecord(e[3], s[0])); CUDA_CHECK(cudaEventSynchronize(e[3])); float tin, tk, tout; CUDA_CHECK(cudaEventElapsedTime(&tin, e[0], e[1])); CUDA_CHECK(cudaEventElapsedTime(&tk, e[1], e[2])); CUDA_CHECK(cudaEventElapsedTime(&tout, e[2], e[3])); float best = engines >= 2 ? fmaxf(tk, fmaxf(tin, tout)) : fmaxf(tk, tin + tout); printf("stages: copy in %.2f ms, kernel %.2f ms, copy out %.2f ms -> best possible overlap ~%.2f ms\n", tin, tk, tout, best); for (int k = 0; k < 4; k++) CUDA_CHECK(cudaEventDestroy(e[k])); } else if (version == 1) { // Depth-first: in -> kernel -> out for chunk 0, then chunk 1, ... for (int c = 0; c < chunks; c++) { copyIn(d_in, h_in, c, s[c % nStreams]); launch(d_in, d_out, c, s[c % nStreams]); copyOut(h_out, d_out, c, s[c % nStreams]); } } else { // Breadth-first: all copies in, then all kernels, then all copies out. for (int c = 0; c < chunks; c++) copyIn(d_in, h_in, c, s[c % nStreams]); for (int c = 0; c < chunks; c++) launch(d_in, d_out, c, s[c % nStreams]); for (int c = 0; c < chunks; c++) copyOut(h_out, d_out, c, s[c % nStreams]); } CUDA_CHECK(cudaGetLastError()); CUDA_CHECK(cudaDeviceSynchronize()); double ms = nowMs() - t0; int errors = 0; for (int i = 0; i < n; i += 997) if (fabsf(h_out[i] - work(h_in[i])) > 1e-5f) errors++; printf("%-14s %7.2f ms errors: %d\n", names[version], ms, errors); ok = ok && errors == 0; } printf(ok ? "PASS\n" : "FAIL\n"); for (int k = 0; k < nStreams; k++) CUDA_CHECK(cudaStreamDestroy(s[k])); CUDA_CHECK(cudaFreeHost(h_in)); CUDA_CHECK(cudaFreeHost(h_out)); CUDA_CHECK(cudaFree(d_in)); CUDA_CHECK(cudaFree(d_out)); return 0; }
The serial run prints how long each stage takes, and the best time overlap could reach: the longest stage if the GPU can copy in both directions at once, otherwise the longer of the kernel and the two copies together. Then it runs the same chunks in two issue orders:
- Depth-first issues copy-in, kernel and copy-out of chunk 0, then of chunk 1, and so on. This is the natural way to write it, and it works well on GPUs with two or more copy engines.
- Breadth-first issues all copy-ins, then all kernels, then all copy-outs. On a GPU with a single copy engine, this order matters. The engine processes copies in the order they were issued, so in depth-first order the copy-out of chunk 0 sits in front of the copy-in of chunk 1 and must wait for kernel 0. That stalls the pipeline.
Measured on a laptop RTX 3070 under Windows (one copy engine): serial 29.4 ms, depth-first 31.3 ms, breadth-first 26.9 ms, against a best possible ~20.4 ms. On Windows the default WDDM driver mode batches submissions, which limits overlap further; on Linux, and on data-center GPUs with several copy engines, the pipelined versions come much closer to the bound. Always measure on the machine you deploy to, and use nsys profile ./pipeline to see the actual timeline.
More streams or chunks are not automatically better. Each chunk adds launch and copy overhead, and small copies don't reach full PCIe bandwidth. Two to four streams and chunks of a few megabytes are a good start.
Events: timing and dependencies
An event is a marker in a stream. The GPU records the time when it reaches it. You have used events for timing since Chapter 3. They also express dependencies between streams without blocking the host:
cudaEvent_t ready; cudaEventCreateWithFlags(&ready, cudaEventDisableTiming); // cheaper when not used for timing produce<<<grid, block, 0, streamA>>>(d_buf); cudaEventRecord(ready, streamA); // marker after 'produce' in stream A cudaStreamWaitEvent(streamB, ready, 0); // stream B waits on the GPU, the host doesn't consume<<<grid, block, 0, streamB>>>(d_buf); // runs only after 'produce' has finished otherWork<<<grid, block, 0, streamA>>>(...); // stream A continues independently
| Call | Who waits | For what |
|---|---|---|
cudaDeviceSynchronize() | host | all work on the device |
cudaStreamSynchronize(s) | host | all work in stream s |
cudaEventSynchronize(e) | host | the point where e was recorded |
cudaStreamWaitEvent(s, e) | stream s (on the GPU) | the point where e was recorded |
cudaStreamQuery(s) / cudaEventQuery(e) | nobody | returns whether the work is done yet |
Calls that synchronize implicitly
Some operations make work in different streams wait for each other even though you didn't ask for it. According to the Programming Guide, operations in two streams cannot overlap if the host issues one of these in between:
- an allocation of pinned host memory (
cudaMallocHost,cudaHostAlloc) - a device memory allocation (
cudaMalloc);cudaFreealso waits for the device - a device memory set (
cudaMemset, the non-Async version) - a memory copy between two addresses in the same device memory
- any operation in the legacy default stream
- a change of the L1 / shared memory configuration
The practical rule: allocate everything up front, use the Async versions of copies and memsets with explicit streams, and keep cudaMalloc and cudaFree out of loops. For allocations that must happen during the work, cudaMallocAsync and cudaFreeAsync are ordered within a stream and don't synchronize the device.
CUDA Graphs
Each kernel launch costs a few microseconds of CPU and driver time. For a kernel that runs for milliseconds, that doesn't matter. For a workload of hundreds of tiny kernels, as in a neural-network step or a simulation timestep, launch overhead can dominate. A CUDA Graph records a whole sequence of operations once and then launches all of it with a single call.
The easiest way to build a graph is stream capture: run your normal stream code between cudaStreamBeginCapture and cudaStreamEndCapture. Nothing executes during capture; the operations are recorded into a graph instead.
#include <cstdio> #include <cstdlib> #include <chrono> #define CUDA_CHECK(call) \ do { \ cudaError_t err_ = (call); \ if (err_ != cudaSuccess) { \ fprintf(stderr, "CUDA error %s at %s:%d\n", \ cudaGetErrorString(err_), __FILE__, __LINE__); \ exit(1); \ } \ } while (0) __global__ void step(float *x, int n) { // a deliberately tiny kernel int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) x[i] = x[i] * 0.5f + 1.0f; } double nowMs() { using namespace std::chrono; return duration<double, std::milli>(steady_clock::now().time_since_epoch()).count(); } int main() { const int n = 4096, kernelsPerStep = 20, steps = 200; float *d_x; CUDA_CHECK(cudaMalloc(&d_x, n * sizeof(float))); cudaStream_t s; CUDA_CHECK(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking)); // Capture one step (20 small launches) into a graph. cudaGraph_t graph; cudaGraphExec_t exec; CUDA_CHECK(cudaStreamBeginCapture(s, cudaStreamCaptureModeGlobal)); for (int k = 0; k < kernelsPerStep; k++) step<<<n / 256, 256, 0, s>>>(d_x, n); CUDA_CHECK(cudaStreamEndCapture(s, &graph)); CUDA_CHECK(cudaGraphInstantiate(&exec, graph, 0)); bool ok = true; for (int version = 0; version < 2; version++) { for (int rep = 0; rep < 2; rep++) { // rep 0 is a warm-up CUDA_CHECK(cudaMemsetAsync(d_x, 0, n * sizeof(float), s)); CUDA_CHECK(cudaStreamSynchronize(s)); double t0 = nowMs(); for (int t = 0; t < steps; t++) { if (version == 0) for (int k = 0; k < kernelsPerStep; k++) step<<<n / 256, 256, 0, s>>>(d_x, n); else CUDA_CHECK(cudaGraphLaunch(exec, s)); } CUDA_CHECK(cudaStreamSynchronize(s)); double ms = nowMs() - t0; if (rep == 1) { float h[n]; CUDA_CHECK(cudaMemcpy(h, d_x, sizeof(h), cudaMemcpyDeviceToHost)); int errors = 0; // x -> x/2 + 1 converges to 2.0 for (int i = 0; i < n; i++) if (h[i] < 1.9999f || h[i] > 2.0001f) errors++; printf("%-14s %d kernels in %7.2f ms (%5.2f us per kernel) errors: %d\n", version == 0 ? "stream launch" : "graph launch", steps * kernelsPerStep, ms, 1000.0 * ms / (steps * kernelsPerStep), errors); ok = ok && errors == 0; } } } printf(ok ? "PASS\n" : "FAIL\n"); CUDA_CHECK(cudaGraphExecDestroy(exec)); CUDA_CHECK(cudaGraphDestroy(graph)); CUDA_CHECK(cudaStreamDestroy(s)); CUDA_CHECK(cudaFree(d_x)); return 0; }
The graph version issues the same 4,000 kernels with one call per step instead of twenty. On a laptop RTX 3070 under Windows the cost per kernel dropped from 7.7 µs to 1.3 µs. How much it saves depends on the driver and operating system; on some systems launches are already cheap and the gain is small. Graphs pay off most when the same sequence repeats many times. Changing kernel arguments afterwards is possible with cudaGraphExecKernelNodeSetParams or by updating the instantiated graph, which is much cheaper than capturing again.
Summary
- A stream is an in-order queue. Different streams are unordered and may overlap.
- Default-stream launches don't block the host. The legacy default stream does serialize with other blocking streams: use non-blocking streams or
--default-stream per-thread. - Overlap requires pinned host memory,
cudaMemcpyAsync, and independent work in different streams. - Chunked pipelines bring the total time close to the longest stage. Measure against a serial baseline.
cudaStreamWaitEventorders streams on the GPU without blocking the host.- Allocation, non-Async memsets and default-stream work cause hidden synchronization.
- CUDA Graphs remove launch overhead for repeated sequences of small kernels.
Exercises
1. Break the overlap. In pipeline.cu, replace cudaMallocHost with malloc for both host buffers (and cudaFreeHost with free). What happens to the pipelined time, and why?
Solution
The pipelined version loses most of its advantage and may become slower than the serial one. With pageable memory, each cudaMemcpyAsync is staged through a driver buffer by the CPU, so copies no longer run in the background while kernels execute. The results are still correct; only the overlap disappears.
2. Find the hidden barrier. Someone adds cudaMemset(d_out, 0, bytes) inside the chunk loop of the pipelined version. What does it do to the timeline?
Solution
The non-Async cudaMemset goes to the legacy default stream and is one of the implicitly synchronizing operations, so every chunk waits for all earlier chunks: the pipeline becomes serial again. It also zeroes output of chunks that are already computed. Use cudaMemsetAsync(ptr, 0, chunkBytes, st) on the chunk only.
3. Chunk count. Run pipeline.cu with 4, 16 and 64 chunks. Explain the trend.
Solution
More chunks shorten the fill and drain at the start and end of the pipeline, so time drops from 4 to 16. With very many chunks each copy is small, per-operation overhead grows, and time rises again. The best value depends on the data size and the GPU.
Check your understanding
Does kernel<<<g, b>>>() without a stream argument block the CPU until the kernel finishes?
No. Every kernel launch is asynchronous with respect to the host, including launches into the default stream.
Two kernels are launched into different streams, but the profiler shows them running one after the other. Name two possible causes.
Either kernel fills the whole GPU, so there is no room for the other to run alongside it; or something between them synchronizes, such as default-stream work, a cudaMalloc or a non-Async cudaMemset.
Further reading & credits
- How to overlap data transfers in CUDA C/C++ (NVIDIA blog)
- CUDA 7 streams simplify concurrency: per-thread default stream (NVIDIA blog)
- Programming Guide: CUDA Graphs
- OLCF CUDA Training Series, part 7: CUDA concurrency
- NVIDIA CUDA C++ Programming Guide — the reference for every API and rule used here
- NVIDIA CUDA C++ Best Practices Guide
The chapter order and topic coverage of this course draw on the OLCF / NERSC CUDA Training Series, the NVIDIA Accelerated Computing Hub CUDA C++ tutorial, the GPU MODE lectures (Apache-2.0) and Simon Boehm's CUDA matrix multiplication worklog (code MIT). The text and example programs on this page are original and were tested on NVIDIA Turing and Ampere GPUs.
Next: a method for finding out why a kernel is slow, and the fixes that matter most. Continue to Performance Optimization.
Practice These Concepts
Reinforce what you just learned with hands-on GPU coding challenges.
Compute the dot product of two vectors on the GPU. The dot product is the sum of element-wise products: result = sum(a[i] * b[i]). Use parallel reduction with shared memory for efficiency. Array size N = 4096.
Sign in to track your progress across challenges.