Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Sparse matrix and matrix multiplication on the GPU

How GPUs implement dense and sparse matrix multiplication, storage formats (CSR/COO/CSC), performance factors (memory bandwidth, arithmetic intensity) and example CUDA programs for dense matmul and CSR sparse matrix-vector multiply.

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

Sparse matrices and matrix multiplication appear in many engineering workloads: simulations, graph algorithms, finite-element analysis, machine learning and scientific computing. An engineer uses GPU implementations to accelerate large dense matrix multiplies (high FLOP workloads) and sparse operations (memory-bound, lower arithmetic intensity) to meet performance targets on hardware.

Key ideas

  • CSR (Compressed Sparse Row): storage format for a sparse matrix A of size m×n with nnz non-zero values. CSR uses three arrays: values[nnz] (all non-zero values), colIdx[nnz] (column index for each value), and rowPtr[m+1] where rowPtr[i] is the start index in values for row i and rowPtr[i+1] is the end (exclusive). Assumes 0-based indexing in typical C/C++ implementations.
    • Exact statement: Given A with rows 0..m-1, let the non-zero entries in row i be stored in contiguous locations values[rowPtr[i] .. rowPtr[i+1]-1] with corresponding column indices colIdx[...] . The arrays satisfy rowPtr[0]=0 and rowPtr[m]=nnz.
  • COO (Coordinate) format: stores triplets (row, col, value) for every non-zero. Simpler but often requires sorting or atomic operations for reductions on GPU.
  • CSC (Compressed Sparse Column): like CSR but compressed by columns; useful when column-wise access (e.g., solving with sparse direct methods) is important. Other GPU-friendly formats include ELL/ELLPACK (fixed nonzeros per row, padded to a uniform width) and HYB (ELL + COO), which improve coalescing at the cost of padding; know when to choose each.
  • SpMV (Sparse Matrix–Vector multiply): compute y = A·x where A is sparse. SpMV is typically memory-bound because each non-zero leads to a load of value and column index and a vector read, with few FLOPs (1 multiply + 1 add).
  • SpMM (Sparse Matrix–Dense Matrix multiply): generalises SpMV when multiplying A by dense matrix B. It allows higher arithmetic intensity if B has many columns.
  • Arithmetic intensity (AI): AI = FLOPs performed / bytes transferred from main memory. High AI favors compute-bound execution; low AI favors memory-bound execution. On GPUs, increasing AI (e.g., reusing data in shared memory or using tiling) improves performance.
  • Roofline model: performance is limited either by peak FLOPS (compute-bound) or by memory bandwidth (bandwidth-bound). The boundary is at AI = peak_FLOPS / peak_bandwidth. For SpMV AI is usually small so it is bandwidth-bound.
  • GPU mapping: For dense matmul each thread often computes one element or a tile; for sparse SpMV a common mapping is one thread per row (CSR) or one warp per row for long rows. Assumptions: rows fit in reasonable work per thread; otherwise use cooperative reduction. Load-balancing options include splitting very long rows across warps/blocks and merge-based or segmented-reduction approaches to avoid atomics while keeping warps well utilized.

Derivation students are commonly asked: show number of arithmetic operations for dense matrix multiplication of A(m×k) and B(k×n): each output element does k multiplications and (k-1) adds ≈ 2k FLOPs. Total FLOPs ≈ 2·m·n·k. Draw diagram: draw two matrices, A on left labeled m×k, B on top labeled k×n, show one element C[i][j] as dot product of row i of A and column j of B; annotate k multiplications and k-1 additions.

When using CSR for SpMV, draw a matrix with zeros and nonzeros; show arrays rowPtr, colIdx, values. Label an example row and show how rowPtr gives the start and end indices.

Formulas

FLOPs_dense = 2·m·n·k — FLOPs for dense matrix multiplication of A(m×k) and B(k×n). m,n,k are dimensionless counts; applies when counting floating-point operations (1 multiply + 1 add counted as 2 FLOPs).

AI = FLOPs / Bytes_transferred — arithmetic intensity. FLOPs in number of floating-point operations, Bytes_transferred in bytes; use to decide bandwidth vs compute domination.

Bandwidth_bound if AI < (Peak_FLOPS / Peak_Bandwidth) — condition from the roofline model. Peak_FLOPS in FLOPs/s, Peak_Bandwidth in bytes/s; AI in FLOPs/byte.

Bytes_SpMV ≈ nnz·(sizeof(value)+sizeof(colIdx)) + (m+1)·sizeof(rowPtr) + T_x + m·sizeof(y) — approximate DRAM traffic for one CSR SpMV, where nnz is number of non-zeros. T_x is the traffic to read x: best-case T_x ≈ n·sizeof(x) if x is well-reused from cache, worst-case T_x ≈ nnz·sizeof(x) with poor reuse. sizeof(value) is 4 or 8 bytes (float/double); sizeof(colIdx) and sizeof(rowPtr) are typically 4 bytes (int). Count only the y store once.

FLOPs_SpMV = 2·nnz — one multiply and one add per non-zero (counting add and multiply separately). Units: FLOPs (dimensionless count of floating ops).

CUDA syntax to remember: __global__ marks a kernel, <<<blocks, threads>>> is kernel launch, threadIdx, blockIdx, blockDim are built-in indices, cudaMalloc, cudaMemcpy, cudaFree for device memory management.

Worked examples

Program 1 — Dense matrix multiply (CUDA): one thread per output element. Compile with nvcc.

#include <stdio.h>
#include <cuda_runtime.h>

__global__ void matmul_kernel(const float* A, const float* B, float* C, int M, int N, int K) {
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    if (row < M && col < N) {
        float sum = 0.0f;
        for (int k = 0; k < K; ++k) sum += A[row*K + k] * B[k*N + col];
        C[row*N + col] = sum;
    }
}

int main() {
    // Example: multiply 2x2 matrices
    int M = 2, K = 2, N = 2;
    float h_A[] = {1,2, 3,4}; // row-major: [ [1,2], [3,4] ]
    float h_B[] = {5,6, 7,8}; // [ [5,6], [7,8] ]
    float h_C[4] = {0};

    float *d_A, *d_B, *d_C;
    cudaMalloc(&d_A, M*K*sizeof(float));
    cudaMalloc(&d_B, K*N*sizeof(float));
    cudaMalloc(&d_C, M*N*sizeof(float));
    cudaMemcpy(d_A, h_A, M*K*sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(d_B, h_B, K*N*sizeof(float), cudaMemcpyHostToDevice);

    dim3 threads(16,16);
    dim3 blocks((N+threads.x-1)/threads.x, (M+threads.y-1)/threads.y);
    matmul_kernel<<<blocks, threads>>>(d_A, d_B, d_C, M, N, K);
    cudaMemcpy(h_C, d_C, M*N*sizeof(float), cudaMemcpyDeviceToHost);

    printf("Result C:\n");
    for (int i = 0; i < M; ++i) {
        for (int j = 0; j < N; ++j) printf("%g ", h_C[i*N+j]);
        printf("\n");
    }

    cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);
    return 0;
}

Sample input: none (program uses hard-coded matrices). Exact output: Result C: 19 22 43 50

Program 2 — CSR Sparse Matrix–Vector multiply (SpMV) in CUDA: one thread per row.

#include <stdio.h>
#include <cuda_runtime.h>

__global__ void spmv_csr_kernel(const int* rowPtr, const int* colIdx, const float* values, const float* x, float* y, int m) {
    int row = blockIdx.x * blockDim.x + threadIdx.x;
    if (row < m) {
        float sum = 0.0f;
        int start = rowPtr[row];
        int end = rowPtr[row+1];
        for (int idx = start; idx < end; ++idx) {
            sum += values[idx] * x[colIdx[idx]];
        }
        y[row] = sum;
    }
}

int main() {
    // Example matrix 3x3 with nnz=5
    // A = [10 0 0; 0 20 30; 40 0 50]
    int m = 3; int nnz = 5;
    int h_rowPtr[] = {0,1,3,5};
    int h_colIdx[] = {0,1,2,0,2};
    float h_values[] = {10,20,30,40,50};
    float h_x[] = {1,2,3};
    float h_y[3] = {0};

    int *d_rowPtr, *d_colIdx; float *d_values, *d_x, *d_y;
    cudaMalloc(&d_rowPtr, (m+1)*sizeof(int));
    cudaMalloc(&d_colIdx, nnz*sizeof(int));
    cudaMalloc(&d_values, nnz*sizeof(float));
    cudaMalloc(&d_x, 3*sizeof(float));
    cudaMalloc(&d_y, m*sizeof(float));

    cudaMemcpy(d_rowPtr, h_rowPtr, (m+1)*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_colIdx, h_colIdx, nnz*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_values, h_values, nnz*sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(d_x, h_x, 3*sizeof(float), cudaMemcpyHostToDevice);

    int threads = 128; int blocks = (m + threads - 1) / threads;
    spmv_csr_kernel<<<blocks, threads>>>(d_rowPtr, d_colIdx, d_values, d_x, d_y, m);
    cudaMemcpy(h_y, d_y, m*sizeof(float), cudaMemcpyDeviceToHost);

    printf("Result y:\n");
    for (int i = 0; i < m; ++i) printf("%g \n", h_y[i]);

    cudaFree(d_rowPtr); cudaFree(d_colIdx); cudaFree(d_values); cudaFree(d_x); cudaFree(d_y);
    return 0;
}

Sample input: none. Exact output: Result y: 10 130 190

Notes on the programs: both examples use float for simplicity and assume a CUDA-capable GPU. Error handling (cudaGetLastError) is omitted for clarity but should be included in production code.

Common mistakes

  • Not considering memory access pattern: in CSR SpMV, accesses to x are irregular; ignoring this and expecting coalesced reads leads to poor performance.
  • Counting FLOPs incorrectly for dense matmul: per output element there are k multiplies and k-1 adds (exactly 2k-1 FLOPs); by convention we approximate the total as 2·m·n·k.
  • Ignoring data types: using int for indices but copying with wrong sizes (e.g., sizeof(long)) leads to memory corruption.
  • Not synchronising or not copying results back from device before printing on host.

For your exam

Types of questions:

  • Definitions: CSR, COO, SpMV, arithmetic intensity — give concise definitions.
  • Short notes: explain why SpMV is memory-bound and methods to improve it (reordering, blocking, using SpMM to increase AI).
  • Derivations: show FLOP count for dense matmul, derive bytes transferred for CSR and compute AI.
  • Programs: small CUDA kernels for dense matmul or CSR SpMV; explain thread mapping and memory usage.
  • Diagrams: draw CSR arrays and annotate one row; draw dot-product mapping for one C[i][j].

What full-marks answers include:

  • Precise definitions with assumptions (indexing base, data type sizes).
  • Correct FLOP counts and memory traffic with units (bytes), and clear statement whether the operation is bandwidth- or compute-bound using roofline.
  • For programs, explain mapping of threads to data, memory copies, and show kernel signature and a brief explanation of shared vs global memory choices.

Quick check

  1. What are the three arrays in CSR and what does each store?
  2. Write the formula for FLOPs for multiplying A(m×k) by B(k×n).
  3. Is SpMV normally compute-bound or bandwidth-bound on GPUs? Give the short reason. Answers: 1) rowPtr (start indices per row), colIdx (column indices of non-zeros), values (non-zero values). 2) FLOPs = 2·m·n·k. 3) Bandwidth-bound — because AI is low (≈2·nnz / bytes_loaded) so memory transfers dominate.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?