Module 13 · Lesson 31 of 98

Streams and overlapping copy with compute

Submit copies and kernels to CUDA streams, use events to express dependencies, and measure the wall-time effect of overlapping transfers with compute on Jetson.

  • Beginner to advanced
  • 8 min read
  • 45 min lab
What you will need

An NVIDIA Jetson with a working CUDA toolkit and nvcc on its supported Linux image for GPU runs. Ubuntu 24.04 in WSL2 or a VM is sufficient for the ordering exercise.

Your place in the module
By the end you can 4 objectives
  • Submit a kernel and asynchronous copies to named CUDA streams.
  • Predict execution order within a stream and across the legacy default stream.
  • Measure a GPU interval and express a cross-stream dependency with CUDA events.
  • Compare wall time for serialised and overlapping submissions.
Video coming soonStreams and overlapping copy with compute
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Memory-bound stencils and where to put the weights
  • A box blur performs few arithmetic operations per byte moved, even with input reuse.
  • A separable filter saves arithmetic, while a materialised intermediate adds a full-image write and read.
  • Mapping the fastest-varying thread index to image columns gives adjacent lanes adjacent pixel addresses, even in a vertical pass.
01

Submit work to named streams

3 min read

You have kernels that compute, but they run one at a time against one copy queue. This lesson answers how streams run copy and compute together and how events time and order them.

Consider a Jetson processing a sequence of images. A stencil for the current image reads input that is already in device memory. While that stencil is running, the program can submit a copy of the next image into a different buffer. The current stencil needs its own input ready before it starts. It has no dependency on the next image. The CUDA Runtime API gives the program a way to express both facts.

A Call cudaStreamCreate(&compute) with a cudaStream_t variable to create a stream. The name compute belongs to your program. The handle can carry a copy, a kernel, or an event. In a kernel launch, the fourth execution configuration argument selects the stream, as in stencil<<<grid, block, 0, compute>>>(input, output). The third argument is the number of bytes of dynamic shared memory. In cudaMemcpyAsync, the last argument selects the stream.

If you submit an upload and then its stencil to the same stream, the stencil sees the uploaded data once it starts. The CPU can submit both commands without waiting for the upload. The host thread returning from a submission call and the device finishing that command are separate milestones. Keep the source of an upload unchanged until the copy completes. Read the destination of a download only after its completion.

Diagram in production
An upload orders the stencil within its own stream. A later image uses separate storage.

In legacy default-stream mode, omitting the stream argument of a kernel launch selects the legacy default stream. Passing 0 as the stream argument of cudaMemcpyAsync selects that default as well. A command submitted to the legacy stream waits for previously submitted work in streams that synchronise with it. Subsequent work in those streams waits for the legacy command. Streams created with cudaStreamCreate participate in this ordering. An accidental launch on the legacy stream can therefore introduce a dependency between operations that use entirely different buffers.

cudaStreamCreateWithFlags(&compute, cudaStreamNonBlocking) creates a stream that is exempt from that implicit legacy ordering. The flag describes the stream's relationship to the legacy stream. Each such stream still preserves its own submission order. CUDA also supports per-thread default-stream mode, where the default stream is local to the host thread and behaves like a regular stream for ordinary submissions. Explicit handles make the intended ordering visible in code. Use the same default-stream mode when comparing builds, especially if the program mixes explicit launches with calls that use the default.

02

Overlap independent copies with a kernel

4 min read

Use two streams for the timing comparison. Put a kernel on compute with its inputs prepared before the trial. Put two host-to-device copies on transfer, each with a separate destination that the kernel will leave untouched. The two copies execute in order. Either copy can run during the kernel, and a sufficiently long kernel can overlap with both in succession. This experiment requires only copy and compute concurrency. It places the two transfers in a single ordered stream.

Use page-locked host storage for both upload sources. cudaMallocHost allocates it and cudaFreeHost releases it. Pageable host buffers can require staging or synchronisation, so the Async suffix alone is insufficient to establish the conditions for this experiment. Allocate and fill the buffers before starting the timer. Keep the host and device buffers alive until both streams finish. The next lesson explains page locking and zero-copy in more detail.

The following statements belong inside a CUDA C++ .cu source built with nvcc. Assume the streams and buffers have been set up, stencil uses separate current-image buffers, and CUDA_CHECK checks a cudaError_t and reports and terminates on failure. The variable serial selects the schedule.

cpp
stencil<<<grid, block, 0, compute>>>(current_in, current_out);
CUDA_CHECK(cudaGetLastError());

cudaStream_t copy_stream = serial ? compute : transfer;
CUDA_CHECK(cudaMemcpyAsync(next_a, host_a, bytes,
                           cudaMemcpyHostToDevice, copy_stream));
CUDA_CHECK(cudaMemcpyAsync(next_b, host_b, bytes,
                           cudaMemcpyHostToDevice, copy_stream));

CUDA_CHECK(cudaStreamSynchronize(compute));
CUDA_CHECK(cudaStreamSynchronize(transfer));

Submit all three operations before either completion wait. A wait between the kernel launch and the first copy would delay submission of both copies until after the kernel finishes. The wait order at the end can stay the same in both modes because both streams have already received all their commands. Check the launch immediately with cudaGetLastError, and check both stream synchronisation calls for failures that surface when queued work completes. Destroy the streams and release the buffers after the trials.

Serialised and two-stream schedulesSerialisedTwo streamsCompute streamKernel, copyA, BKernelTransfer streamIdleCopy A, copyBPossible overlapNoneKernel withcopiesHost completionWait for bothWait for both
The serialised schedule places all work in one stream. The two-stream schedule permits each copy to coincide with the kernel.

Query cudaGetDeviceProperties for the active CUDA device and inspect asyncEngineCount. A positive count indicates support for asynchronous copy engines and the possibility of overlapping transfers with kernel execution under suitable conditions. The measured gain depends on the workload and the board. On Jetson, copies and kernels can compete for the same system DRAM bandwidth. A stencil that already uses much of that bandwidth may slow down while a copy is active. If the kernel finishes before the second transfer starts, only the first transfer has a chance to overlap.

For wall time, use clock_gettime(CLOCK_MONOTONIC, ...) immediately before the kernel launch and again after both stream waits. Check the clock calls for errors and subtract the start timestamp from the finish timestamp, accounting for both seconds and nanoseconds. The interval includes host submission overhead, device work and the wait for completion. Linux's monotonic clock avoids jumps from changes to the system's calendar time.

Warm up both modes before collecting samples. Swap which mode runs first across repeated comparisons and keep the kernel, byte counts and validation identical. Check the two copied destinations and the stencil result outside the timed interval. Report the median for each mode and subtract the two-stream median from the serial median. A positive difference is a reduction in wall time. Small or negative differences are valid measurements. With very short operations, submission overhead and variation can dominate. Larger transfers or a longer kernel can make the comparison easier to interpret. The wall-time difference quantifies the effect of changing the schedule. It cannot identify which copy overlapped or for how long from that measurement alone.

Going deeperExplore the mechanism

Query the stream priority range with cudaDeviceGetStreamPriorityRange and request a priority with cudaStreamCreateWithPriority. Lower numeric values mean higher priority. Priority is a scheduling hint for pending work, chiefly kernel work. A high-priority launch gives no guarantee that an already executing block will be preempted or that a transfer will start sooner.

On hardware with Hyper-Q, multiple hardware work queues can reduce false dependencies that arise when independent streams share a submission queue. CUDA streams and hardware queues need not map one to one. concurrentKernels in cudaDeviceProp reports whether the device supports concurrent kernels. The architecture sets an upper bound on resident kernel grids, and the workload determines how much of that capacity it can use. Blocks from different grids need available SM resources, including block slots, registers and shared memory. A kernel that occupies every eligible slot can leave room for just one running grid until blocks retire. Smaller grids can leave room for several. To determine how many actually ran together for a given launch mix, inspect overlapping kernel execution on a device timeline for that run. Counting stream handles gives only the number of streams the program created.

03

Use events to time work and express dependencies

3 min read

A cudaEventCreate creates a timing-capable event. cudaEventRecord places it in a specified stream. A successful record call means the host has submitted that marker. For instance, the CPU can submit a stop marker while the kernel it follows is still running.

To time a kernel, submit a start event, the kernel and a stop event to the same stream. Wait for the stop event on the host before reading the elapsed time. The start event precedes the stop event in that stream, so the stop wait also establishes that the start event has completed.

cpp
cudaEvent_t start, stop;
CUDA_CHECK(cudaEventCreate(&start));
CUDA_CHECK(cudaEventCreate(&stop));
CUDA_CHECK(cudaEventRecord(start, compute));
stencil<<<grid, block, 0, compute>>>(current_in, current_out);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaEventRecord(stop, compute));
CUDA_CHECK(cudaEventSynchronize(stop));

float kernel_ms = 0.0f;
CUDA_CHECK(cudaEventElapsedTime(&kernel_ms, start, stop));
CUDA_CHECK(cudaEventDestroy(start));
CUDA_CHECK(cudaEventDestroy(stop));

cudaEventElapsedTime reports milliseconds between the two recorded markers. The interval can include scheduling delays and contention while other streams are active. A stop marker on compute establishes completion of the work preceding it on compute. To measure total wall time for both branches of the comparison, keep the CPU clock and both completion waits. Event times for individual streams help explain a result, but adding two intervals can count simultaneous execution twice.

Use a recorded event for ordering when a kernel consumes data uploaded on another stream. Suppose transfer uploads next_a, and a kernel submitted to compute uses that buffer. Record input_ready on transfer immediately after the upload. Before submitting the consumer, call cudaStreamWaitEvent(compute, input_ready, 0). CUDA delays work submitted after that wait in compute until the recorded event completes. The host can continue submitting work. Commands already submitted ahead of the wait in compute keep their earlier position.

Upload completion orders a consumerHostTransfer streamConsumer streamSubmit copy ARecord ready eventSubmit copy BSubmit event waitSubmit consumer kernelCopy A ready1. Host → Transfer streamSubmit copy A2. Host → Transfer streamRecord ready event3. Host → Transfer streamSubmit copy B4. Host → Consumer streamSubmit event wait5. Host → Consumer streamSubmit consumer kernel6. Transfer stream → ConsumerstreamCopy A ready
Recording after the first copy lets its consumer proceed while the second copy is still eligible to run.

Record the event before submitting the wait. A stream wait uses the recording current at the time of the wait call, and waiting on an event that has never been recorded has no effect. In the two-copy schedule, place the record between the first and second copies if the consumer needs only the first destination. If it needs both, record after the second copy. If the CPU needs to inspect a result or reuse a host buffer, cudaEventSynchronize can wait on a marker recorded after that operation. Choose the marker by the last operation that must finish before access is safe.

The next lesson, Pinned memory and zero-copy, explains why the kind of host memory matters for asynchronous copies and when a Jetson kernel can access a host buffer directly.

Key takeaways

  • Commands in a stream execute in submission order.
  • Independent copies and kernels in different streams may overlap when hardware and memory conditions allow.
  • An event records a point in a stream and can support timing or enforce a cross-stream dependency.
  • End-to-end wall time includes submission and completion waits for both streams.
Reflect
  1. Explain to a colleague, in two sentences: submit a kernel and asynchronous copies to named CUDA streams.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close