LeetKernels
ProblemsStart solving
Problems

75. Sparse Matrix-Dense Matrix Multiplication medium

Implement a GPU program that multiplies a sparse matrix A of dimensions M × N by a dense matrix B of dimensions N × K, producing a dense output matrix C of dimensions M × K. All matrices are stored in row-major order using 32-bit floats. The matrix A is approximately 60–70% sparse (i.e., 60–70% of elements are zero), and nnz gives the number of non-zero elements in A.

Mathematically, the operation is defined as: Cij​=k=0∑N−1​Aik​⋅Bkj​fori=0,…,M−1,j=0,…,K−1

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 matrix C

Example

Input:
Matrix A (3×4): ​2.00.00.0​0.03.00.0​0.00.04.0​1.00.00.0​​ Matrix B (4×2): ​1.03.05.07.0​2.04.06.08.0​​ Output:
Matrix C (3×2): ​9.09.020.0​12.012.024.0​​

Constraints

  • 1 ≤ M, N, K ≤ 8,192
  • All values in A and B are 32-bit floats in the range [−10, 10]
  • The matrix A is approximately 60–70% sparse
  • Performance is measured with M = 4,096, N = 2,048, K = 512

Starter code (CUDA)

#include <cuda_runtime.h>

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

Solve it on your GPU

Previous: GPT-2 Transformer BlockNext: Adder Transformer Inference

From LeetGPU, CC BY-NC-ND 4.0.