CUDA Tutorials for Matrices and Sparse Kernels¶
Matrices are the backbone of scientific computing, computer graphics, and deep learning, and GPUs accelerate them by mapping two-dimensional grids of threads onto row-major memory layouts. This section walks through five hands-on CUDA tutorials covering dense matrix multiplication, structural property checks, everyday matrix transformations, Compressed Sparse Row multiplication, and multi-GPU sharding.
How to Compile and Run¶
- Every tutorial below is a self-contained CUDA C++ source file stored inside
chapter 19 - CUDA and GPU programming/cuda. If you have a local NVIDIA GPU with the CUDA Toolkit installed, open a terminal in thatcudadirectory and compile any file withnvcc.
- If you do not have a local NVIDIA GPU, you can run every example for free on a Google Colab T4 GPU. Switch the runtime to a T4 GPU, write the source file into the notebook workspace with
%%writefile, and invoke!nvccin the next cell.
- Unlike 1D vector kernels that launch scalar integer counts, matrix kernels use CUDA's
dim3struct to launch 2D grids of 2D thread blocks. A typical configuration pairs a \(16 \times 16\) block (dim3 blockSize(16, 16), giving \(256\) threads per block) with a ceiling-divided griddim3 gridSize((width + blockSize.x - 1) / blockSize.x, (height + blockSize.y - 1) / blockSize.y), ensuring the grid covers every matrix entry even when dimensions are not exact multiples of \(16\). Inside the kernel, each thread computes its coordinates withrow = blockIdx.y * blockDim.y + threadIdx.yandcol = blockIdx.x * blockDim.x + threadIdx.x, then guards against out-of-bounds threads withif (row < height && col < width).
Tutorial 11 Dense Matrix Multiplication¶
- Given two matrices \(A \in \mathbb{R}^{m \times n}\) and \(B \in \mathbb{R}^{n \times p}\), their product is a new matrix \(C = AB \in \mathbb{R}^{m \times p}\) whose entry at row \(i\) and column \(j\) is the dot product of row \(i\) of \(A\) with column \(j\) of \(B\).
- Geometrically, matrix multiplication applies a linear transformation to vectors in space, making it the core primitive behind coordinate transforms, solving linear systems, rotations and scaling in graphics, and every linear layer in a neural network. It is associative and distributive, though not commutative (\(AB \neq BA\) in general).
- Rather than launching a separate
vectorDotkernel for every output cell (which would drown execution time in kernel launch overhead), CUDA assigns one thread per output element \(C_{\text{row}, \text{col}}\) using 2D thread indexing over a flattened row-major array (row * width + col). - No atomic operations are required because every thread writes to its own unique address
c[row * width + col], completely eliminating write-write race conditions. - From a memory coalescing standpoint, adjacent threads in a warp hold consecutive
col(threadIdx.x) values while sharing the samerow. That makes reads fromb[idx * width + col]and writes toc[row * width + col]contiguous and cleanly coalesced, whilea[row * width + idx]is read from the same address and broadcast across the warp. - Notice one compact teaching simplification in this first matrix snippet. The host allocates buffers of size
width * heightfora,b, andcwithwidth = 6andheight = 4, while the inner loop walksidxfrom0towidth - 1and indexesb[idx * width + col]. For general rectangular products (\(m \times k\) times \(k \times p\)), you should pass all three dimensions separately, as demonstrated later in Tutorial 15.
Find the full source in 11.matrixMul.cu, then compile and run it from the cuda directory.
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void matrixMul(const float *a, const float *b, float *c, int width, int height) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
float value = 0;
for (int idx = 0; idx < width; ++idx) {
value += a[row * width + idx] * b[idx * width + col];
}
c[row * width + col] = value;
}
}
float randomFloat(int randMax = 1000){
return static_cast<float>(rand()) / static_cast<float>(randMax);
}
int main(){
srand(time(0));
int width = 6;
int height = 4;
size_t size = width * height * sizeof(float);
float *hostA, *hostB, *hostC;
float *deviceA, *deviceB, *deviceC;
hostA = (float*) malloc(size);
hostB = (float*) malloc(size);
hostC = (float*) malloc(size);
for (int i = 0; i < width * height; i++){
hostA[i] = randomFloat();
hostB[i] = randomFloat();
}
cudaMalloc((void**)&deviceA, size);
cudaMalloc((void**)&deviceB, size);
cudaMalloc((void**)&deviceC, size);
cudaMemcpy(deviceA, hostA, size, cudaMemcpyHostToDevice);
cudaMemcpy(deviceB, hostB, size, cudaMemcpyHostToDevice);
dim3 threadsPerBlock(16, 16);
dim3 blocksPerGrid((width + threadsPerBlock.x - 1) / threadsPerBlock.x, (height + threadsPerBlock.y - 1) / threadsPerBlock.y);
matrixMul<<<blocksPerGrid, threadsPerBlock>>>(deviceA, deviceB, deviceC, width, height);
cudaMemcpy(hostC, deviceC, size, cudaMemcpyDeviceToHost);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
std::cout << hostC[i * width + j] << " ";
}
std::cout << std::endl;
}
free(hostA);
free(hostB);
free(hostC);
cudaFree(deviceA);
cudaFree(deviceB);
cudaFree(deviceC);
}
Tutorial 12 Matrix Properties via Index Arithmetic¶
- Many structural matrix checks in CUDA boil down to pure 2D index arithmetic. Instead of looping sequentially on the CPU, we initialise a single boolean flag to
truein device memory and let every thread inspect its own(row, col)entry in parallel, flipping*result = falsewhenever a rule is broken. - A Toeplitz matrix has constant values along every descending diagonal from top-left to bottom-right, meaning \(A_{i, j} = A_{i-1, j-1}\) for every \(i > 0\) and \(j > 0\). Convolution operators in signal processing naturally take this form.
- A diagonal matrix vanishes everywhere off the main diagonal, meaning \(A_{i, j} = 0\) for all \(i \neq j\). Diagonal scaling is cheap because only \(n\) entries carry information.
- A symmetric matrix equals its own transpose (\(A = A^\top\)), meaning \(A_{i, j} = A_{j, i}\) for every pair of indices. Covariance matrices and undirected graph adjacency matrices share this symmetry.
- A skew-symmetric matrix equals the negative of its transpose (\(A = -A^\top\)), meaning \(A_{i, j} = -A_{j, i}\) for all \(i, j\) (which automatically forces every main diagonal entry to be zero since \(A_{i, i} = -A_{i, i}\)).
- In linear algebra, an idempotent matrix satisfies \(A^2 = A\) under matrix multiplication. To keep all five kernels purely index-local without invoking a full matrix multiply,
isIdempotentbelow tests the element-wise condition \(A_{i, j} = A_{i, j}^2\), which checks whether every entry is \(0\) or \(1\) and agrees with the matrix-product definition on diagonal matrices. - Notice why concurrent writes of
*result = falsebehave predictably here without atomics. Every violating thread writes the exact same boolean value (false), so whichever thread reaches global memory last leavesfalseintact. In general reductions where threads combine distinct values, you should use atomics or a parallel reduction instead.
Find the full source in 12.matrixProperties.cu, then compile and run it from the cuda directory.
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
// Matrix operations in CUDA are often achieved with index manipulation, these kernels demonstrates these.
__global__ void isToeplitz(const float *a, int width, int height, bool *result) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
if (row > 0 && col > 0) {
if (a[row * width + col] != a[(row - 1) * width + (col - 1)]) {
*result = false;
}
}
}
}
__global__ void isDiagonal(const float *a, int width, int height, bool *result) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
if (row != col) {
if (a[row * width + col] != 0) {
*result = false;
}
}
}
}
__global__ void isSymmetric(const float *a, int width, int height, bool *result) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
if (a[row * width + col] != a[col * width + row]) {
*result = false;
}
}
}
__global__ void isSkewSymmetric(const float *a, int width, int height, bool *result) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
if (a[row * width + col] != -a[col * width + row]) {
*result = false;
}
}
}
__global__ void isIdempotent(const float *a, int width, int height, bool *result) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
if (a[row * width + col] != a[row * width + col] * a[row * width + col]) {
*result = false;
}
}
}
int main() {
int width = 4;
int height = 4;
float *hostMatrix = (float*)malloc(width * height * sizeof(float));
bool *hostToeplitzResult = (bool*)malloc(sizeof(bool));
bool *hostDiagonalResult = (bool*)malloc(sizeof(bool));
bool *hostSymmetricResult = (bool*)malloc(sizeof(bool));
bool *hostSkewSymmetricResult = (bool*)malloc(sizeof(bool));
bool *hostIdempotentResult = (bool*)malloc(sizeof(bool));
float *deviceMatrix;
bool *deviceToeplitzResult;
bool *deviceDiagonalResult;
bool *deviceSymmetricResult;
bool *deviceSkewSymmetricResult;
bool *deviceIdempotentResult;
cudaMalloc((void**)&deviceMatrix, width * height * sizeof(float));
cudaMalloc((void**)&deviceToeplitzResult, sizeof(bool));
cudaMalloc((void**)&deviceDiagonalResult, sizeof(bool));
cudaMalloc((void**)&deviceSymmetricResult, sizeof(bool));
cudaMalloc((void**)&deviceSkewSymmetricResult, sizeof(bool));
cudaMalloc((void**)&deviceIdempotentResult, sizeof(bool));
srand(time(NULL));
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
hostMatrix[i * width + j] = rand() % 10;
}
}
*hostToeplitzResult = true;
*hostDiagonalResult = true;
*hostSymmetricResult = true;
*hostSkewSymmetricResult = true;
*hostIdempotentResult = true;
cudaMemcpy(deviceMatrix, hostMatrix, width * height * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(deviceToeplitzResult, hostToeplitzResult, sizeof(bool), cudaMemcpyHostToDevice);
cudaMemcpy(deviceDiagonalResult, hostDiagonalResult, sizeof(bool), cudaMemcpyHostToDevice);
cudaMemcpy(deviceSymmetricResult, hostSymmetricResult, sizeof(bool), cudaMemcpyHostToDevice);
cudaMemcpy(deviceSkewSymmetricResult, hostSkewSymmetricResult, sizeof(bool), cudaMemcpyHostToDevice);
cudaMemcpy(deviceIdempotentResult, hostIdempotentResult, sizeof(bool), cudaMemcpyHostToDevice);
dim3 blockSize(2, 2);
dim3 gridSize((width + blockSize.x - 1) / blockSize.x, (height + blockSize.y - 1) / blockSize.y);
isToeplitz<<<gridSize, blockSize>>>(deviceMatrix, width, height, deviceToeplitzResult);
isDiagonal<<<gridSize, blockSize>>>(deviceMatrix, width, height, deviceDiagonalResult);
isSymmetric<<<gridSize, blockSize>>>(deviceMatrix, width, height, deviceSymmetricResult);
isSkewSymmetric<<<gridSize, blockSize>>>(deviceMatrix, width, height, deviceSkewSymmetricResult);
isIdempotent<<<gridSize, blockSize>>>(deviceMatrix, width, height, deviceIdempotentResult);
cudaMemcpy(hostToeplitzResult, deviceToeplitzResult, sizeof(bool), cudaMemcpyDeviceToHost);
cudaMemcpy(hostDiagonalResult, deviceDiagonalResult, sizeof(bool), cudaMemcpyDeviceToHost);
cudaMemcpy(hostSymmetricResult, deviceSymmetricResult, sizeof(bool), cudaMemcpyDeviceToHost);
cudaMemcpy(hostSkewSymmetricResult, deviceSkewSymmetricResult, sizeof(bool), cudaMemcpyDeviceToHost);
cudaMemcpy(hostIdempotentResult, deviceIdempotentResult, sizeof(bool), cudaMemcpyDeviceToHost);
if (*hostToeplitzResult) {
std::cout << "Matrix is Toeplitz" << std::endl;
} else {
std::cout << "Matrix is not Toeplitz" << std::endl;
}
if (*hostDiagonalResult) {
std::cout << "Matrix is Diagonal" << std::endl;
} else {
std::cout << "Matrix is not Diagonal" << std::endl;
}
if (*hostSymmetricResult) {
std::cout << "Matrix is Symmetric" << std::endl;
} else {
std::cout << "Matrix is not Symmetric" << std::endl;
}
if (*hostSkewSymmetricResult) {
std::cout << "Matrix is Skew Symmetric" << std::endl;
} else {
std::cout << "Matrix is not Skew Symmetric" << std::endl;
}
if (*hostIdempotentResult) {
std::cout << "Matrix is Idempotent" << std::endl;
} else {
std::cout << "Matrix is not Idempotent" << std::endl;
}
free(hostMatrix);
free(hostToeplitzResult);
free(hostDiagonalResult);
free(hostSymmetricResult);
free(hostSkewSymmetricResult);
free(hostIdempotentResult);
cudaFree(deviceMatrix);
cudaFree(deviceToeplitzResult);
cudaFree(deviceDiagonalResult);
cudaFree(deviceSymmetricResult);
cudaFree(deviceSkewSymmetricResult);
cudaFree(deviceIdempotentResult);
return 0;
}
Tutorial 13 Transpose, Trace, and Scalar Broadcasting¶
- This tutorial puts three everyday linear algebra primitives into one clean file and intentionally uses stack-allocated host arrays (
float hostA[width * height]) instead ofmallocandfree, showing that CUDA can feel just as natural as standard C++ for small prototypes. - Matrix transpose flips rows and columns so that \(C = A^\top\), where \(C_{j, i} = A_{i, j}\). In row-major memory this maps
a[row * width + col]toc[col * height + row]. Notice the memory coalescing trade-off hidden in that one line. Adjacent threads in a warp read consecutive floats froma, which coalesces cleanly, yet write tocwith a stride ofheight, which splits memory transactions on large matrices. High-performance transpose kernels solve this by staging a square tile into fast__shared__memory first and writing out coalesced rows. - Matrix trace sums the entries along the main diagonal of a square matrix, \(\operatorname{tr}(A) = \sum_{i=0}^{n-1} A_{i, i}\). On the \(3 \times 3\) example containing \(1\) through \(9\), the trace is \(1 + 5 + 9 = 15\). Watch out for an important concurrency subtlety in
c[0] += a[row * width + col]. On a tiny \(3 \times 3\) matrix this often appears to work, yet on larger matrices multiple diagonal threads race to read, add, and writec[0]simultaneously, losing updates. Production trace kernels replace+=withatomicAdd(&c[0], a[row * width + col])or a parallel shared-memory reduction. - Scalar broadcasting applies a single scalar \(\alpha\) across every element of the matrix (\(C_{i, j} = \alpha A_{i, j}\)). Because each thread reads one contiguous element and writes one contiguous element with zero coordination between threads, broadcasting is embarrassingly parallel and strictly limited by global memory bandwidth.
Find the full source in 13.matrixOperations.cu, then compile and run it from the cuda directory.
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void matrixTranspose(const float *a, float *c, int width, int height) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
c[col * height + row] = a[row * width + col];
}
}
__global__ void matrixTrace(const float *a, float *c, int width, int height) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
if (row == col) {
c[0] += a[row * width + col];
}
}
}
__global__ void matrixBroadcast(const float *a, float *c, int width, int height, float scalar) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height && col < width) {
c[row * width + col] = a[row * width + col] * scalar;
}
}
void printMatrix(const float *matrix, int width, int height) {
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
std::cout << matrix[i * width + j] << " ";
}
std::cout << "\n";
}
}
int main() {
// Matrixes are rather initialised without dynamic memory allocation.
// This is to show CUDA can also feel natural.
const int width = 3;
const int height = 3;
float hostA[width * height];
float hostC[width * height] = {0};
float hostTrace[1] = {0};
float scalar = 2.0f;
for (int i = 0; i < width * height; ++i) {
hostA[i] = static_cast<float>(i + 1);
}
std::cout << "Original Matrix:\n";
printMatrix(hostA, width, height);
float *deviceA, *deviceC, *deviceTrace;
size_t size = width * height * sizeof(float);
cudaMalloc(&deviceA, size);
cudaMalloc(&deviceC, size);
cudaMalloc(&deviceTrace, sizeof(float));
cudaMemcpy(deviceA, hostA, size, cudaMemcpyHostToDevice);
cudaMemcpy(deviceTrace, hostTrace, sizeof(float), cudaMemcpyHostToDevice);
dim3 blockSize(16, 16);
dim3 gridSize((width + blockSize.x - 1) / blockSize.x, (height + blockSize.y - 1) / blockSize.y);
matrixTranspose<<<gridSize, blockSize>>>(deviceA, deviceC, width, height);
cudaMemcpy(hostC, deviceC, size, cudaMemcpyDeviceToHost);
std::cout << "\nTransposed Matrix:\n";
printMatrix(hostC, height, width);
matrixTrace<<<gridSize, blockSize>>>(deviceA, deviceTrace, width, height);
cudaMemcpy(hostTrace, deviceTrace, sizeof(float), cudaMemcpyDeviceToHost);
std::cout << "\nTrace of the Matrix: " << hostTrace[0] << "\n";
matrixBroadcast<<<gridSize, blockSize>>>(deviceA, deviceC, width, height, scalar);
cudaMemcpy(hostC, deviceC, size, cudaMemcpyDeviceToHost);
std::cout << "\nMatrix after broadcasting with scalar " << scalar << ":\n";
printMatrix(hostC, width, height);
cudaFree(deviceA);
cudaFree(deviceC);
cudaFree(deviceTrace);
return 0;
}
Tutorial 14 Sparse Matrix Multiplication in CSR Format¶
- Real-world matrices in graph analytics, finite-element physics, recommender systems, and pruned neural networks are often more than \(99\%\) zeros. Storing and multiplying those zeros wastes both memory capacity and GPU bandwidth, so industry code stores only the non-zero values in a compact structure called Compressed Sparse Row (CSR) format.
- CSR packs a sparse matrix with \(m\) rows and \(\text{nnz}\) non-zero entries into three flat arrays.
valstores every non-zero value in row-major order,colIndstores the column index of each non-zero, androwPtr(of length \(m + 1\)) stores the starting offset of each row insidevalandcolInd, withrowPtr[m] = nnz. Row \(i\) therefore spans indicesrowPtr[i]throughrowPtr[i + 1] - 1. - Consider a concrete \(3 \times 3\) matrix \(M\) with five non-zero entries.
- In CSR form, that matrix compresses to
val = [1, 2, 3, 4, 5],colInd = [0, 2, 2, 0, 1], androwPtr = [0, 2, 3, 5]. Row \(0\) starts at offset \(0\) and ends before \(2\) (giving \((0, 0) = 1\) and \((0, 2) = 2\)), row \(1\) spans offset \(2\) to \(3\) (giving \((1, 2) = 3\)), and row \(2\) spans offset \(3\) to \(5\) (giving \((2, 0) = 4\) and \((2, 1) = 5\)). - To multiply two CSR matrices \(A\) and \(B\) into a dense output \(C\),
sparseMatrixMulKernelassigns one thread per row of \(A\) using a 1D grid (row = blockIdx.x * blockDim.x + threadIdx.x). For each output columncol, the thread walks only the non-zero entriesidxAof rowrowin \(A\), reads their column indexcolA = deviceColIndA[idxA], jumps directly to rowcolAof \(B\) viadeviceRowPtrB[colA], and accumulatesdeviceValA[idxA] * deviceValB[idxB]wheneverdeviceColIndB[idxB] == col. - Notice a clean software engineering habit introduced here. All GPU memory management (
cudaMalloc,cudaMemcpy,cudaMemset, kernel launch, andcudaFree) is encapsulated inside a host wrapper functionsparseMatrixMul, leavingmainfree to express the problem cleanly withstd::vector. - Sparse kernels illustrate why GPU optimisation gets harder once access patterns become data-dependent. Indirect lookups (
deviceRowPtrB[colA]) break memory coalescing, and rows with wildly different non-zero counts create load imbalance and warp divergence, which is why production libraries such as cuSPARSE use merge-path balancing and warp-level row cooperation.
Find the full source in 14.matrixMulSparse.cu, then compile and run it from the cuda directory.
#include <iostream>
#include <vector>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
__global__ void sparseMatrixMulKernel(
const int *deviceRowPtrA,
const int *deviceColIndA,
const float *deviceValA,
const int *deviceRowPtrB,
const int *deviceColIndB,
const float *deviceValB,
float *deviceC,
int rowsA,
int colsB
) {
int row = blockIdx.x * blockDim.x + threadIdx.x;
if (row < rowsA) {
for (int col = 0; col < colsB; ++col) {
float sum = 0.0f;
for (int idxA = deviceRowPtrA[row]; idxA < deviceRowPtrA[row + 1]; ++idxA) {
int colA = deviceColIndA[idxA];
for (int idxB = deviceRowPtrB[colA]; idxB < deviceRowPtrB[colA + 1]; ++idxB) {
if (deviceColIndB[idxB] == col) {
sum += deviceValA[idxA] * deviceValB[idxB];
}
}
}
deviceC[row * colsB + col] = sum;
}
}
}
void sparseMatrixMul(
const std::vector<int>& hostRowPtrA,
const std::vector<int>& hostColIndA,
const std::vector<float>& hostValA,
const std::vector<int>& hostRowPtrB,
const std::vector<int>& hostColIndB,
const std::vector<float>& hostValB,
std::vector<float>& hostC,
int rowsA,
int colsB
) {
int *deviceRowPtrA, *deviceColIndA, *deviceRowPtrB, *deviceColIndB;
float *deviceValA, *deviceValB, *deviceC;
int nnzA = hostValA.size();
int nnzB = hostValB.size();
size_t sizeC = rowsA * colsB * sizeof(float);
cudaMalloc(&deviceRowPtrA, hostRowPtrA.size() * sizeof(int));
cudaMalloc(&deviceColIndA, nnzA * sizeof(int));
cudaMalloc(&deviceValA, nnzA * sizeof(float));
cudaMalloc(&deviceRowPtrB, hostRowPtrB.size() * sizeof(int));
cudaMalloc(&deviceColIndB, nnzB * sizeof(int));
cudaMalloc(&deviceValB, nnzB * sizeof(float));
cudaMalloc(&deviceC, sizeC);
cudaMemcpy(deviceRowPtrA, hostRowPtrA.data(), hostRowPtrA.size() * sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(deviceColIndA, hostColIndA.data(), nnzA * sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(deviceValA, hostValA.data(), nnzA * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(deviceRowPtrB, hostRowPtrB.data(), hostRowPtrB.size() * sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(deviceColIndB, hostColIndB.data(), nnzB * sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(deviceValB, hostValB.data(), nnzB * sizeof(float), cudaMemcpyHostToDevice);
cudaMemset(deviceC, 0, sizeC);
int blockSize = 256;
int numBlocks = (rowsA + blockSize - 1) / blockSize;
sparseMatrixMulKernel<<<numBlocks, blockSize>>>(
deviceRowPtrA,
deviceColIndA,
deviceValA,
deviceRowPtrB,
deviceColIndB,
deviceValB,
deviceC,
rowsA,
colsB);
cudaMemcpy(hostC.data(), deviceC, sizeC, cudaMemcpyDeviceToHost);
cudaFree(deviceRowPtrA);
cudaFree(deviceColIndA);
cudaFree(deviceValA);
cudaFree(deviceRowPtrB);
cudaFree(deviceColIndB);
cudaFree(deviceValB);
cudaFree(deviceC);
}
int main() {
int rowsA = 3;
int colsB = 3;
std::vector<int> hostRowPtrA = {0, 2, 4, 4};
std::vector<int> hostColIndA = {0, 2, 1, 2};
std::vector<float> hostValA = {1.0f, 2.0f, 3.0f, 4.0f};
std::vector<int> hostRowPtrB = {0, 2, 3, 4};
std::vector<int> hostColIndB = {0, 1, 2, 0};
std::vector<float> hostValB = {5.0f, 6.0f, 7.0f, 8.0f};
std::vector<float> hostC(rowsA * colsB, 0.0f);
sparseMatrixMul(
hostRowPtrA,
hostColIndA,
hostValA,
hostRowPtrB,
hostColIndB,
hostValB,
hostC,
rowsA,
colsB);
std::cout << "Result Matrix C:\n";
for (int i = 0; i < rowsA; ++i) {
for (int j = 0; j < colsB; ++j) {
std::cout << hostC[i * colsB + j] << " ";
}
std::cout << "\n";
}
return 0;
}
Tutorial 15 Multi-GPU Sharded Matrix Multiplication¶
- When a matrix multiplication grows too large for a single GPU's memory or compute budget, sharding partitions the workload across multiple devices. Here
matrixMultiplyShardedqueries the number of installed GPUs withcudaGetDeviceCount(&numGpus)and switches active context withcudaSetDevice(gpuIndex)for each shard. - The decomposition splits \(A \in \mathbb{R}^{m \times k}\) horizontally into \(G\) row blocks \(A^{(0)}, \dots, A^{(G-1)}\), where each GPU receives
rowsPerGpu = numRowsA / numGpusrows and the final GPU absorbs any remainder (remainingRows = numRowsA % numGpus). Matrix \(B \in \mathbb{R}^{k \times p}\) is replicated to every GPU so each device can independently compute its output horizontal strip without inter-GPU communication.
- Notice how
matrixMulKernelhere generalises Tutorial 11 to arbitrary rectangular shapes by taking all three dimensions (numRowsA,numColsA,numColsB), computing a \(1024 \times 512\) by \(512 \times 1024\) product and copying each finished shard directly into its destination offsetmatrixC + startRow * numColsBon the host. Even on a single-GPU machine (such as a Colab T4),numGpusevaluates to \(1\) and the code runs cleanly without changes. - Because the loop calls synchronous
cudaMemcpybefore moving to the nextgpuIndex, each GPU finishes before the next one begins. To overlap execution across real multi-GPU nodes, you would allocate per-GPU streams (with pinned host memory andcudaMemcpyAsync) or launch one host thread per device so all GPUs execute their shards concurrently. - Inside each GPU, the next major leap in throughput comes from shared-memory tiling (blocking). In the straightforward
matrixMulKernelbelow, every thread reads \(k\) elements of \(A\) and \(k\) elements of \(B\) from slow global memory, meaning every float of \(A\) is fetched \(p\) times and every float of \(B\) is fetched \(m\) times. By cooperatively loadingBLOCK_SIZE\(\times\)BLOCK_SIZEtiles of \(A\) and \(B\) into on-chip__shared__memory, calling__syncthreads(), and accumulating partial dot products across tiles, a block reuses each loaded floatBLOCK_SIZEtimes and slashes global memory traffic by a factor ofBLOCK_SIZE(a \(16\times\) reduction for \(16 \times 16\) tiles).
Find the full source in 15.matrixMulSharded.cu, then compile and run it from the cuda directory.
#include <iostream>
#include <cuda_runtime.h>
#define BLOCK_SIZE 16
__global__ void matrixMulKernel(
const float* matrixA,
const float* matrixB,
float* matrixC,
int numRowsA,
int numColsA,
int numColsB
) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < numRowsA && col < numColsB) {
float value = 0;
for (int k = 0; k < numColsA; ++k) {
value += matrixA[row * numColsA + k] * matrixB[k * numColsB + col];
}
matrixC[row * numColsB + col] = value;
}
}
void matrixMultiplySharded(
const float* matrixA,
const float* matrixB,
float* matrixC,
int numRowsA,
int numColsA,
int numColsB
) {
int numGpus;
cudaGetDeviceCount(&numGpus);
int rowsPerGpu = numRowsA / numGpus;
int remainingRows = numRowsA % numGpus;
float** hostMatrixCChunks = new float*[numGpus];
for (int gpuIndex = 0; gpuIndex < numGpus; ++gpuIndex) {
cudaSetDevice(gpuIndex);
int startRow = gpuIndex * rowsPerGpu;
int endRow = startRow + rowsPerGpu;
if (gpuIndex == numGpus - 1) {
endRow += remainingRows;
}
int chunkRows = endRow - startRow;
size_t sizeAChunk = chunkRows * numColsA * sizeof(float);
size_t sizeCChunk = chunkRows * numColsB * sizeof(float);
float *deviceMatrixA, *deviceMatrixB, *deviceMatrixC;
cudaMalloc(&deviceMatrixA, sizeAChunk);
cudaMalloc(&deviceMatrixB, numColsA * numColsB * sizeof(float));
cudaMalloc(&deviceMatrixC, sizeCChunk);
cudaMemcpy(deviceMatrixA, matrixA + startRow * numColsA, sizeAChunk, cudaMemcpyHostToDevice);
cudaMemcpy(deviceMatrixB, matrixB, numColsA * numColsB * sizeof(float), cudaMemcpyHostToDevice);
dim3 blockDim(BLOCK_SIZE, BLOCK_SIZE);
dim3 gridDim((numColsB + BLOCK_SIZE - 1) / BLOCK_SIZE, (chunkRows + BLOCK_SIZE - 1) / BLOCK_SIZE);
matrixMulKernel<<<gridDim, blockDim>>>(
deviceMatrixA,
deviceMatrixB,
deviceMatrixC,
chunkRows,
numColsA,
numColsB);
cudaMemcpy(matrixC + startRow * numColsB, deviceMatrixC, sizeCChunk, cudaMemcpyDeviceToHost);
cudaFree(deviceMatrixA);
cudaFree(deviceMatrixB);
cudaFree(deviceMatrixC);
}
delete[] hostMatrixCChunks;
}
void fillMatrix(float* matrix, int rows, int cols) {
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
matrix[row * cols + col] = static_cast<float>(rand()) / RAND_MAX;
}
}
}
int main() {
int numRowsA = 1024;
int numColsA = 512;
int numRowsB = numColsA;
int numColsB = 1024;
size_t sizeA = numRowsA * numColsA * sizeof(float);
size_t sizeB = numRowsB * numColsB * sizeof(float);
size_t sizeC = numRowsA * numColsB * sizeof(float);
float *matrixA = (float*)malloc(sizeA);
float *matrixB = (float*)malloc(sizeB);
float *matrixC = (float*)malloc(sizeC);
fillMatrix(matrixA, numRowsA, numColsA);
fillMatrix(matrixB, numRowsB, numColsB);
matrixMultiplySharded(matrixA, matrixB, matrixC, numRowsA, numColsA, numColsB);
free(matrixA);
free(matrixB);
free(matrixC);
return 0;
}
Take-Home¶
- Mapping matrices onto 2D thread grids (
dim3) lets each thread compute its coordinates(row, col)directly and turn linear algebra formulas into flat row-major index arithmetic (row * width + col). - Memory access geometry determines performance as much as arithmetic complexity. Coalesced reads along
col(threadIdx.x) fly through GPU memory controllers, while strided writes (naive transpose) and indirect lookups (CSR sparse indexing) pay heavy latency penalties unless mitigated with shared-memory staging or load-balanced scheduling. - Concurrency correctness depends on whether threads write to distinct outputs or shared state. Matrix multiplication, transpose, and scalar broadcasting need no synchronisation because every thread owns a unique output slot, whereas reductions such as matrix trace require
atomicAddor parallel shared-memory reduction at scale. - Compressed Sparse Row (CSR) format (
val,colInd,rowPtr) eliminates wasted storage and redundant multiplications on sparse matrices, while encapsulatingcudaMalloc, transfers, and kernel launches inside a host wrapper keeps calling code clean and maintainable. - Scaling dense matrix multiplication follows two complementary axes, namely row-sharding work across multiple GPUs with
cudaGetDeviceCount,cudaSetDevice, and asynchronous streams, and tiling blocks through on-chip__shared__memory inside each GPU to cut global memory traffic by a factor ofBLOCK_SIZE.