GPU by Example
15 / 16

Scaling up

6 min readChapter 15 of 16

One GPU is a lot of throughput. Sometimes it is not enough — and then the problem becomes communication. This chapter covers the two ways CUDA scales: more GPUs, and tighter cooperation inside one GPU.

Many GPUs, one process#

Every CUDA call targets the current device. Switch with cudaSetDevice:

two_gpus.cuCUDA C++
int count = 0;
cudaGetDeviceCount(&count);

cudaSetDevice(0);
float* d0;
cudaMalloc(&d0, bytes);
kernel<<<grid, block>>>(d0);

cudaSetDevice(1);
float* d1;
cudaMalloc(&d1, bytes);
kernel<<<grid, block>>>(d1);

A pointer belongs to the device that allocated it. Using d0 while device 1 is current is an error (or, with peer access, a remote access). Streams are also per-device.

Peer access#

By default, GPU 0 cannot read GPU 1's memory. On systems with PCIe or NVLink, you can enable peer access:

CUDA C++
int can = 0;
cudaDeviceCanAccessPeer(&can, 0, 1);
if (can) {
    cudaSetDevice(0);
    cudaDeviceEnablePeerAccess(1, 0);
}

Then copy directly between devices, without staging through the host:

CUDA C++
cudaMemcpyPeer(d1, 1, d0, 0, bytes);                 // sync
cudaMemcpyPeerAsync(d1, 1, d0, 0, bytes, stream);    // async
APIPurpose
cudaGetDeviceCountHow many GPUs
cudaSetDeviceSelect the current device
cudaGetDevicePropertiesName, memory, SMs, compute capability
cudaDeviceCanAccessPeerIs direct access possible?
cudaDeviceEnablePeerAccessTurn it on
cudaMemcpyPeer / ...AsyncDevice-to-device copy

Peer copies over PCIe are still slow compared with local HBM. NVLink is much faster (hundreds of GB/s), which is why multi-GPU servers pay for it.

The hard part is the algorithm#

Splitting work across GPUs is easy. Making it fast is not:

  • Communication is the new bottleneck. A model-parallel layer that exchanges gigabytes per step will spend most of its time on the link.
  • Synchronisation is global. Every rank must finish before the next phase; the slowest GPU sets the pace.
  • Data layout matters more. A transpose between GPUs costs more than a transpose in shared memory.
  • Failure modes multiply. One GPU out of memory, one rank slower, one link degraded.

Amdahl's law applies at machine scale: if 10% of the work is serial or communication-bound, a second GPU buys at most ~1.8×, and a third buys almost nothing.

NCCL: the collective library#

For multi-GPU deep learning, do not hand-roll all-reduce. NVIDIA's NCCL implements ring and tree collectives over PCIe, NVLink, and InfiniBand:

CUDA C++
#include <nccl.h>

ncclComm_t comm;
ncclCommInitRank(&comm, nranks, unique_id, rank);

ncclAllReduce(sendbuf, recvbuf, count, ncclFloat, ncclSum,
              comm, stream);

The usual deployment is one process per GPU (launched by mpirun, torchrun, or a scheduler). Each process calls cudaSetDevice(rank) and participates in the collective with the same unique_id.

Thread block clusters#

Clusters are the intra-GPU answer to the same problem: how do blocks cooperate without going through global memory?

A cluster is a group of thread blocks that are guaranteed to be co-resident on one GPC. Blocks in a cluster can:

  • synchronise with cluster.sync(),
  • read and write each other's shared memory through distributed shared memory (DSMEM).

Requirements: compute capability 9.0 or newer (Hopper, Blackwell), and the cluster must fit in a GPC.

Declaring a cluster#

Static shape, via the launch bounds attribute:

CUDA C++
__global__ void __cluster_dims__(2, 1, 1) clusterKernel(...) {
    // 2 blocks per cluster
}

clusterKernel<<<4, 256>>>(...);   // 4 blocks = 2 clusters

Or dynamic shape, via the extensible launch API:

CUDA C++
cudaLaunchConfig_t config = {};
config.gridDim = 4;
config.blockDim = 256;

cudaLaunchAttribute attr = {};
attr.id = cudaLaunchAttributeClusterDimension;
attr.val.clusterDim = {2, 1, 1};
config.attrs = &attr;
config.numAttrs = 1;

cudaLaunchKernelEx(&config, clusterKernel, args...);

The cluster shape divides the grid: a grid of 4 blocks with a cluster of 2 forms two clusters. Clusters do not change blockIdx; they add a position within the cluster.

Distributed shared memory#

Each block's shared memory is addressable by every block in its cluster:

cluster_exchange.cuCUDA C++
#include <cooperative_groups.h>
namespace cg = cooperative_groups;

__global__ void __cluster_dims__(2, 1, 1)
clusterExchange(int* out) {
    extern __shared__ int smem[];
    cg::cluster_group cluster = cg::this_cluster();

    smem[threadIdx.x] = blockIdx.x * 100 + threadIdx.x;
    cluster.sync();                       // all blocks initialized

    int rank = cluster.block_rank();
    int* peer = cluster.map_shared_rank(smem, 1 - rank);
    out[blockIdx.x * blockDim.x + threadIdx.x] = peer[threadIdx.x];

    cluster.sync();                       // no block exits while peer reads
}

Launch it with two blocks of 256 threads and one int of dynamic shared memory per thread:

CUDA C++
clusterExchange<<<2, 256, 256 * sizeof(int)>>>(d_out);

Each thread writes into its own block's shared memory, then reads the other block's value. The result is a swap:

Output
block 0 wrote 0..255      reads 100..355 from block 1
block 1 wrote 100..355    reads 0..255 from block 0

The two cluster.sync() calls are mandatory:

  • Before reading, so every block has written.
  • Before exiting, so no block frees its shared memory while a peer is still reading it.

When clusters help#

  • Fusing two blocks that would otherwise communicate through global memory.
  • Implementing a distributed histogram or reduction across a small group.
  • Producer/consumer pipelines where one block's output feeds another block's shared memory.
  • Algorithms that need a cheaper barrier than a full grid sync.

They are a Hopper+ feature and require a cooperative-style launch; do not build a library around them unless you can require CC 9.0.

Unified memory across devices#

Managed memory can migrate between GPUs, but it does so at page granularity and on demand. That is rarely the fastest way to move data:

CUDA C++
cudaMemPrefetchAsync(data, bytes, device_id, stream);

Explicit cudaMemcpyPeerAsync is usually better for bulk transfers, and NCCL is better for collectives.

A scaling checklist#

  • Measure one GPU first. Scaling a slow kernel multiplies the slowness.
  • Find the communication volume. Bytes per iteration × iterations per second = required bandwidth.
  • Pick the link. PCIe, NVLink, InfiniBand; know the numbers.
  • Overlap. Communication streams, compute streams, events.
  • Check the serial fraction. Amdahl's law is not optional.
  • Use collectives, not point-to-point spaghetti. NCCL knows the topology.
  • Test with one GPU missing. Failure handling is part of scaling.

Exercises#

  • Query all GPUs and print name, memory, SM count, and compute capability. Which pairs support peer access?
  • Why must cudaDeviceEnablePeerAccess be called on the source device? What does it enable?
  • In the cluster example, remove the second cluster.sync(). What race does it introduce?
  • Estimate the all-reduce time for a 1 GB gradient vector over PCIe 4.0 (25 GB/s) vs NVLink (400 GB/s). Compare with a 10 ms compute step.
  • Read the NCCL documentation for ncclAllReduce and explain the difference between the ring and tree algorithms.

Next: the cheat sheet — every syntax rule and API in one place.