Programming heterogeneous clusters
How to program heterogeneous clusters: combining CPUs and GPUs across nodes using MPI, CUDA (or OpenCL), data partitioning, communication strategies (GPU-aware MPI, GPU Direct RDMA), and performance models for correct and efficient distributed heterogeneous execution.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Heterogeneous clusters combine general-purpose CPUs and accelerator GPUs across multiple machines (nodes). Engineers use them to scale high-performance tasks (simulation, machine learning, and scientific computing) so programs run faster by using many devices correctly and efficiently.
Key ideas
- Host — the CPU and its memory on a node. Device — an accelerator (GPU) and its memory attached to that host.
- MPI (Message Passing Interface) — a standard API for exchanging messages between processes on different nodes; the common functions used are MPI_Init, MPI_Comm_size, MPI_Comm_rank, MPI_Send, MPI_Recv, MPI_Gather and MPI_Finalize. MPI is used to coordinate work across nodes.
- CUDA-aware MPI — an MPI implementation that can accept GPU (device) pointers directly for MPI calls; it avoids explicit host-device copies by integrating with CUDA runtime.
- NVIDIA GPUDirect RDMA — a hardware + driver facility that allows the GPU memory on one node to be read/written directly by the NIC for remote DMA, removing host copies and lowering latency. Requires NIC and driver support.
- Unified Memory — CUDA feature where the system and device memory are managed by the runtime to present a single logical address space to the program; simplifies programming but can hide expensive page migrations.
- Work partitioning — how to split the global task into parts assigned to CPUs and GPUs across nodes. Two common strategies:
- Data parallel partitioning (domain decomposition) — split data by ranges (for example split a vector into contiguous blocks) and give each block to a rank/device.
- Task parallel partitioning — different ranks or devices perform different algorithmic tasks (pipelines, stages).
- Static scheduling — partition decided at startup (simple, low runtime overhead). Dynamic scheduling — use a master-worker or distributed queue to balance load at runtime (handles heterogeneity but adds communication/coordination overhead).
- Performance cost model (basic, exam style): total wall time for a partition on a node = compute time + local memory transfer + network communication. A simple linear model: T_total = T_comp + T_comm where T_comp depends on throughput (FLOPS/sec) and T_comm depends on data size and network/bandwidth/latency.
- For domain decomposition where each node processes n elements and sends back results of size s bytes, T_comm ≈ latency + s / bandwidth (assume simple store-and-forward). List assumptions when using this model (no congestion, homogeneous NIC, contention-free).
- Correctness conditions: data must be partitioned without overlap or with well-defined overlap (ghost regions) and synchronization must ensure no rank reads not-yet-produced remote data.
Diagrams to draw for exam answers:
- Cluster diagram: two or three nodes; inside each node draw CPU, host memory, GPU with device memory, and NIC. Draw arrows showing host-to-device copy and NIC connections between nodes. Label arrows: H2D, D2H, NIC (RDMA).
- Data partition diagram: a 1D array divided into blocks; show which rank handles which indices and where boundary exchange (halo) occurs.
Formulas
For a programming topic we list syntax to remember and small cost formulas.
MPI_Init(&argc, &argv) — initialize MPI environment.
MPI_Comm_size(MPI_COMM_WORLD, &size) — get number of ranks (processes).
MPI_Comm_rank(MPI_COMM_WORLD, &rank) — get this process rank ID.
MPI_Send(buf, count, MPI_BYTE, dest, tag, MPI_COMM_WORLD) — send a host buffer to another rank.
MPI_Recv(buf, count, MPI_BYTE, src, tag, MPI_COMM_WORLD, &status) — receive into a host buffer.
MPI_Scatter(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, MPI_COMM_WORLD) — distribute equal blocks from root.
MPI_Gather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, root, MPI_COMM_WORLD) — gather equal blocks to root.
cudaMalloc(void** devPtr, size_t size) — allocate device (GPU) memory.
cudaSetDevice(int device) — select which GPU this process uses (important on multi-GPU nodes).
cudaMemcpy(void* dst, const void* src, size_t count, cudaMemcpyKind kind) — copy between host and device.
cudaFree(void* devPtr) — free device memory.
kernel<<<grid, block>>>(args...) — launch a CUDA kernel with grid and block dimensions.
T_total = T_comp + T_comm — simple runtime model; T_comp depends on device throughput and data size, T_comm ≈ latency + (message_size / bandwidth).
Units: sizes in bytes, time in seconds. Always state assumptions: model ignores contention, start-up cost per kernel launch and per MPI call.
Worked examples
Example 1 — MPI + CUDA vector add (run with mpirun -np 2). This splits a vector between ranks; each rank runs the GPU kernel on its block and rank 0 gathers results and prints them.
Code (save as vec_add_mpi_cuda.cu and compile with: nvcc -ccbin mpicxx vec_add_mpi_cuda.cu -o vec_add_mpi_cuda && mpirun -np 2 ./vec_add_mpi_cuda — actual compile command depends on system; check MPI+CUDA toolchain):
#include <mpi.h>
#include <cuda_runtime.h>
#include <stdio.h>
#include <stdlib.h>
__global__ void vecAdd(const float* A, const float* B, float* C, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) C[i] = A[i] + B[i];
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
const int N = 8; // total length
int local_n = N / size; // assume divides evenly for exam clarity
float *h_A = NULL, *h_B = NULL, *h_C = NULL;
if (rank == 0) {
h_A = (float*)malloc(N * sizeof(float));
h_B = (float*)malloc(N * sizeof(float));
h_C = (float*)malloc(N * sizeof(float));
for (int i = 0; i < N; ++i) { h_A[i] = (float)i; h_B[i] = 100.0f + i; }
}
float *local_A = (float*)malloc(local_n * sizeof(float));
float *local_B = (float*)malloc(local_n * sizeof(float));
float *local_C = (float*)malloc(local_n * sizeof(float));
// scatter data from rank 0
MPI_Scatter(h_A, local_n, MPI_FLOAT, local_A, local_n, MPI_FLOAT, 0, MPI_COMM_WORLD);
MPI_Scatter(h_B, local_n, MPI_FLOAT, local_B, local_n, MPI_FLOAT, 0, MPI_COMM_WORLD);
// allocate device buffers
float *d_A, *d_B, *d_C;
cudaMalloc((void**)&d_A, local_n * sizeof(float));
cudaMalloc((void**)&d_B, local_n * sizeof(float));
cudaMalloc((void**)&d_C, local_n * sizeof(float));
cudaMemcpy(d_A, local_A, local_n * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, local_B, local_n * sizeof(float), cudaMemcpyHostToDevice);
int block = 128;
int grid = (local_n + block - 1) / block;
vecAdd<<<grid, block>>>(d_A, d_B, d_C, local_n);
cudaDeviceSynchronize();
cudaMemcpy(local_C, d_C, local_n * sizeof(float), cudaMemcpyDeviceToHost);
// gather results to rank 0
MPI_Gather(local_C, local_n, MPI_FLOAT, h_C, local_n, MPI_FLOAT, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("Result vector C:\n");
for (int i = 0; i < N; ++i) printf("%g ", h_C[i]);
printf("\n");
}
// cleanup
cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);
free(local_A); free(local_B); free(local_C);
if (rank == 0) { free(h_A); free(h_B); free(h_C); }
MPI_Finalize();
return 0;
}
Sample run and exact output (when run with 2 ranks): Assume mpirun -np 2 ./a.out Output:
Result vector C: 100 102 104 106 108 110 112 114
(Explanation: A = [0..7], B = [100..107], sum = [100..114].)
Example 2 — Single-node heterogeneous split: CPU + GPU cooperative vector add. This runs without MPI. CPU computes first half, GPU second half.
Code (save as vec_add_cpu_gpu.cu; compile with nvcc -std=c++11 vec_add_cpu_gpu.cu -o vec_add_cpu_gpu -Xcompiler -pthread):
#include <cuda_runtime.h>
#include <stdio.h>
#include <thread>
__global__ void vecAddGPU(const float* A, const float* B, float* C, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) C[i] = A[i] + B[i];
}
void cpuAdd(const float* A, const float* B, float* C, int start, int n) {
for (int i = 0; i < n; ++i) C[start + i] = A[start + i] + B[start + i];
}
int main() {
const int N = 10;
float A[N], B[N], C[N];
for (int i = 0; i < N; ++i) { A[i] = (float)i; B[i] = 10.0f + i; }
int mid = N/2; // CPU handles [0,mid-1], GPU handles [mid,N-1]
// launch CPU thread
std::thread cpu_thread(cpuAdd, A, B, C, 0, mid);
// GPU part
int gpu_n = N - mid;
float *d_A, *d_B, *d_C;
cudaMalloc((void**)&d_A, gpu_n * sizeof(float));
cudaMalloc((void**)&d_B, gpu_n * sizeof(float));
cudaMalloc((void**)&d_C, gpu_n * sizeof(float));
cudaMemcpy(d_A, A + mid, gpu_n * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, B + mid, gpu_n * sizeof(float), cudaMemcpyHostToDevice);
int block = 128;
int grid = (gpu_n + block - 1) / block;
vecAddGPU<<<grid, block>>>(d_A, d_B, d_C, gpu_n);
cudaDeviceSynchronize();
cudaMemcpy(C + mid, d_C, gpu_n * sizeof(float), cudaMemcpyDeviceToHost);
cpu_thread.join();
printf("C = ");
for (int i = 0; i < N; ++i) printf("%g ", C[i]);
printf("\n");
cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);
return 0;
}
Sample run and exact output: ./vec_add_cpu_gpu Output: C = 10 12 14 16 18 20 22 24 26 28
(Explanation: A = [0..9], B = [10..19], sum = [10, 12, 14, 16, 18, 20, 22, 24, 26, 28].)
Note to reviewer: the compile/link commands depend on local MPI and CUDA setup; the code is exam-standard and demonstrates concepts.
Common mistakes
- Assuming GPU Direct RDMA is available — it requires specific NIC and driver support.
- Overlapping communication and computation incorrectly without synchronization (forgetting cudaDeviceSynchronize or MPI_Wait when needed).
- Transferring more data than needed (not packing or sending whole buffers instead of subarrays).
- Not considering PCIe or NVLink transfer costs: copying host↔device is expensive and often dominates small kernels.
- Launching very small kernels per MPI message — kernel launch overhead kills performance.
- Not setting a unique CUDA device per MPI rank on multi-GPU nodes; use cudaGetDeviceCount/cudaSetDevice or CUDA_VISIBLE_DEVICES to map ranks to GPUs.
- Using pageable host memory for large H2D/D2H transfers; prefer cudaMallocHost/cudaHostRegister (pinned memory) to improve bandwidth and enable faster DMA paths.
For your exam
Types of questions you will get:
- Definitions: define heterogeneous cluster, NVIDIA GPUDirect RDMA, CUDA-aware MPI. Include diagrams and assumptions.
- Short notes: describe work partitioning strategies (static vs dynamic), or compare CPU+GPU scheduling approaches.
- Derivations: show a cost model T = T_comp + T_comm and derive communication time for a block exchange: T_comm = latency + (bytes / bandwidth).
- Programs: write an MPI+GPU pseudocode or short program to scatter data, compute on GPUs, gather results. Full marks: correct MPI calls, correct host/device memory handling, synchronization points and mention of error checking.
- Diagrams: draw node internals (CPU/GPU/host memory/device memory/NIC) and label H2D/D2H and network links; show halo exchange in domain decomposition.
Full-marks answers include clearly stated assumptions (data sizes, homogeneous nodes or not), correct sequence of operations (scatter/copy/compute/copy/gather), error handling note (check return codes), and a performance discussion (where time is spent and ways to optimize: overlapping, GPU-aware MPI, reducing transfers, use of Unified Memory with caution). Mention overlapping using CUDA streams and non-blocking MPI (MPI_Isend/MPI_Irecv/MPI_Wait) where appropriate.
Quick check
- What is NVIDIA GPUDirect RDMA? 2) Why might you use dynamic scheduling across heterogeneous devices? 3) In MPI+CUDA code, when must you copy device results back to host? Answers: NVIDIA GPUDirect RDMA lets the NIC perform DMA directly to/from GPU device memory (bypassing host copies); dynamic scheduling adapts to different device speeds and runtime variability to balance load; you must copy device results back to host before using MPI calls that do not accept device pointers (unless MPI is CUDA-aware) or before host code reads them.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?