LeetKernels
ProblemsStart solving
Problems

18. Sparse Matrix-Vector Multiplication medium

Implement a GPU program that performs sparse matrix-vector multiplication. Given a sparse matrix A of dimensions M×N and a dense vector x of length N, compute the product vector y=A×x, which will have length M. A is stored in row-major order. nnz is the number of non-zero elements in A.

Mathematically, the operation is defined as: yi​=j=0∑N−1​Aij​⋅xj​fori=0,1,…,M−1

The matrix A is approximately 60 - 70% sparse.

Implementation Requirements

  • Use only GPU native features (external libraries are not permitted)
  • The solve function signature must remain unchanged
  • The final result must be stored in vector y

Example:

Input:
Matrix A (3×4): ​5.00.00.0​0.02.00.0​0.03.00.0​1.00.04.0​​ Vector x: ​1.02.03.04.0​​ Output:
Vector y: ​9.013.016.0​​

Constraints

  • 1 ≤ M, N ≤ 10,000
  • The matrix A is approximately 60-70% sparse (i.e., 60-70% of elements are zero)
  • Performance is measured with M = 1,000, N = 10,000

Starter code (CUDA)

#include <cuda_runtime.h>

// A, x, y are device pointers
extern "C" void solve(const float* A, const float* x, float* y, int M, int N, int nnz) {}

Solve it on your GPU

Previous: Dot ProductNext: Reverse Array

From LeetGPU, CC BY-NC-ND 4.0.