ELLMEngineering Large
Language Models
Download PDF

Chapter 28

Host-Device Orchestration, Streams, and CUDA Graphs

On this page

A fast kernel can sit inside a slow application. Transfers, allocations, launch submission, synchronization, and shape management determine whether kernel speed reaches the user.

The previous section gave a resource model inside one kernel. The running example does not live there. A decode step is a short sequence of kernels, copies, and sampling work submitted from the host or a captured graph. This section is the shell around that sequence: how work is ordered, overlapped, and kept off the global critical path.

The asynchronous execution contract

CUDA calls usually enqueue work into streams. Operations in one stream execute in order. Independent operations in different streams may overlap if dependencies, resources, and hardware engines allow it. "May overlap" is important: concurrency is permitted, not guaranteed.

An event records progress in a stream. Another stream can wait on that event without forcing the host to synchronize the whole device. This builds a dependency graph while preserving unrelated concurrency.

Example status: CUDA excerpt; not compiled or benchmarked.

cudaEvent_t ready;
cudaEventCreateWithFlags(&ready, cudaEventDisableTiming);

cudaMemcpyAsync(d_x, h_x, bytes, cudaMemcpyHostToDevice, copy_stream);
cudaEventRecord(ready, copy_stream);
cudaStreamWaitEvent(compute_stream, ready, 0);
kernel<<<grid, block, 0, compute_stream>>>(d_x, d_y, n);

Avoid cudaDeviceSynchronize() in a request path unless a full-device boundary is truly required. It converts independent queues into a global critical path and can hide the operation that actually created an error.

Overlapping transfer and compute

Host-device overlap normally requires pinned host memory, asynchronous copy APIs, distinct streams, hardware support, and independent buffers. Double buffering partitions input into chunks:

  1. copy chunk i + 1 to device;
  2. compute chunk i;
  3. copy result i - 1 to host.

Chunk size balances transfer efficiency, pipeline fill/drain, and working-set memory. Tiny chunks pay submission overhead; huge chunks leave little overlap.

Pinned memory should be pooled. Pinning and unpinning are heavyweight, and excessive pinned memory harms the operating system by reducing pageable capacity.

Default-stream hazards

Legacy default-stream semantics can synchronize with work in other streams. Per-thread default streams and nonblocking streams provide different behavior. Production code should choose a convention explicitly rather than rely on compilation defaults that vary across components.

Libraries may enqueue work on a caller-provided stream or an internal stream. Document stream ownership and lifetime. A tensor cannot be freed, reused, or modified until all streams that access it have completed their dependencies.

Stream priorities and fairness

Stream priority is a scheduling hint, not a deadline guarantee. A high-priority kernel cannot preempt every already-running block. Long-running persistent kernels and huge blocks can therefore delay latency-sensitive work even when placed in a higher-priority stream.

Design cooperative yielding or partition capacity when strict service isolation matters. Measure interference using the production mixture, not isolated streams.

Allocation on the critical path

Synchronous allocation can introduce global coordination. Stream-ordered allocation with cudaMallocAsync and cudaFreeAsync ties lifetime to stream progress and lets the runtime reuse a memory pool.

Pool policy includes release threshold, device and process scope, cross-stream dependencies, fragmentation, and warmup. A fast allocator does not excuse unbounded temporary memory. Track high-water mark and reserve behavior.

CUDA Graphs

A CUDA Graph represents a repeated dependency graph of kernels, copies, and supported memory operations. Instantiating the graph performs setup once; launching the executable graph reduces repeated CPU submission overhead.

Graphs are valuable when:

  • the sequence of operations repeats;
  • kernel work is small enough that launch overhead matters;
  • addresses and shapes are stable or can be updated within supported limits;
  • the application can manage graph variants and lifetimes.

Graphs are less useful when the workload changes structure every iteration, graph updates are frequent and expensive, or one long kernel dominates latency.

In the decode regime of the running example, each step may launch several short kernels: RoPE or cache append, attention, MLP GEMMs, normalization, logits, and sampling. If measured CPU dispatch and launch gaps are comparable to the short GPU work at small batch, submission becomes visible. Graph capture amortizes that overhead for stable shape buckets; there is no universal per-launch latency to assume across runtimes and hardware.

Example status: CUDA excerpt; not compiled or benchmarked.

cudaGraph_t graph;
cudaGraphExec_t graph_exec;

cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal);
stage1<<<g1, b1, 0, stream>>>(a, tmp);
stage2<<<g2, b2, 0, stream>>>(tmp, out);
cudaStreamEndCapture(stream, &graph);

cudaGraphInstantiate(&graph_exec, graph, nullptr, nullptr, 0);
for (int step = 0; step < steps; ++step) {
  cudaGraphLaunch(graph_exec, stream);
}

Graph executables and captured resources have ownership constraints. Reusing one executable graph concurrently may be restricted. Graph memory nodes and stream-ordered allocations have GPU-ordered lifetimes that must be respected.

Shape buckets and graph variants

LLM engines often maintain graph variants for batch and token-count buckets. Padding to a captured shape trades extra device work for stable launch overhead and addresses. Too many buckets create compilation, memory, and test burden.

Choose buckets from traffic distribution and kernel sensitivity. Keep a general eager fallback. Track hit rate, padded work, graph memory, and update failures.

For the running example, a decode graph family might cover B in {1, 2, 4, 8} with a small set of context-length buckets. Padding eight sequences to the next captured length is acceptable only when the saved launch latency exceeds the wasted KV and GEMM work.

Multi-GPU copies and peer access

Device-to-device transfers can use peer access over the available interconnect. The relevant path may be PCIe, NVLink, or another fabric, with topology-dependent bandwidth and routing. Batch small transfers, preserve alignment, and overlap communication only when independent compute exists.

For collectives, use a collective library rather than hand-rolled peer copies unless the communication pattern is genuinely unusual. The application-level question is still exposed communication on the critical path, not theoretical link bandwidth.

Prove the lifetime of a staging slot

For tile j, distinguish four events: H_j, host staging writes complete; C_j, host-to-device copy complete; K_j, the kernel's last read complete; and R_j, the result copy complete. Correctness requires H_j -> C_j -> K_j -> R_j. A pinned input slot may be rewritten after C_j; its device input allocation may be overwritten only after K_j; a pinned output slot may be read after R_j. These are three different reuse boundaries.

With q cyclic slots, assigning slot=j mod q does not enforce those edges. Record an event after the operation that releases each resource. A GPU stream can wait on the event before reusing a device slot; host code must observe completion before overwriting or reading host memory. An event recorded before the last consumer is an incorrect ownership proof even if the measured run happens to serialize.

For constant copy time c and kernel time k, independent engines and enough slots give the lower-bound makespan c+k+(n-1)*max(c,k) for n copy/kernel pairs. This excludes output copies and assumes no shared bandwidth bottleneck. Add the return-copy stage to the dependency graph if results leave the device. Derive throughput from the slowest contended resource, rather than applying the two-stage expression to a three-stage pipeline.

End-to-end timing

CPU wall-clock timing around an asynchronous launch measures submission, not completion. CUDA events measure elapsed device time between points in a stream. End-to-end latency should use the product boundary and include queueing, copies, and synchronization.

Example status: CUDA excerpt; not compiled or benchmarked.

cudaEventRecord(start, stream);
kernel<<<grid, block, 0, stream>>>(args);
cudaEventRecord(stop, stream);
cudaEventSynchronize(stop);
cudaEventElapsedTime(&milliseconds, start, stop);

Warm up context creation, allocations, JIT compilation, graph upload, and caches according to the claim. Report both cold and warm behavior when users encounter both.

Design Exercises

  1. What conditions are required to overlap a host-device copy with compute?
  2. Why can cudaDeviceSynchronize() destroy concurrency?
  3. When do CUDA Graphs help, and when do they not?
  4. How would you choose graph shape buckets for an inference engine?
  5. Design a double-buffered input pipeline and name its failure modes.

Worked Solutions

1. Copy-compute overlap

The copy must be asynchronous, host memory should normally be pinned, source and destination buffers must not conflict with compute, the work must be in streams without an ordering dependency, and hardware must support the required concurrent engines. Overlap can still be limited by shared copy engines, memory bandwidth contention, or a chunk too small to amortize submission.

2. Device synchronization

cudaDeviceSynchronize() waits for all previously submitted work on the device, including independent streams. It inserts a host-visible global boundary, prevents pipelining across iterations, and can turn recoverable queue slack into latency. Prefer events or stream synchronization scoped to the dependency actually required.

3. CUDA Graphs

Graphs help repeated fine-grained workloads where CPU launch and runtime setup are visible. They do not accelerate the instructions inside a dominant kernel. They lose value when topology, shapes, addresses, or operation sequences change so frequently that capture, update, or variant management exceeds the saved launch cost.

4. Graph buckets

Measure the joint distribution of batch size, token count, and model path. Choose a small set that captures most traffic with tolerable padding, while capping executable-graph memory and compile time. Route unusual shapes to an eager fallback. Optimize hit rate and saved latency against padded FLOPs and variant ownership, not bucket count alone.

5. Double buffering

Allocate two or more host and device buffers. While compute consumes buffer A, copy the next input into B and return the prior output from another buffer. Connect stages with events. Failure modes include overwriting a buffer before its consumer completes, using pageable memory, chunks too small or large, hidden default-stream synchronization, copy and compute contending for memory bandwidth, and missing backpressure when the producer outruns the GPU.