LeetKernels
ProblemsStart solving
Problems

22. General Matrix Multiplication (GEMM) medium

Implement a basic General Matrix Multiplication (GEMM). Given matrix A of dimensions M×K, matrix B of dimensions K×N, input/output matrix C of dimensions M×N, and scalar multipliers α and β, compute the operation: C=α⋅(A×B)+β⋅Cinitial​

The input matrices A, B, and the initial state of C contain 16-bit floating-point numbers (FP16/half). All matrices are stored in row-major order. The scalars α and β are 32-bit floats.

Implementation Requirements

  • Use only native features (external libraries other than WMMA are not permitted).
  • The solve function signature must remain unchanged.
  • Accumulation during multiplication should use FP32 for better precision before converting the final result to FP16.
  • The final result must be stored back into matrix C as half.

Example:

Input:
(Note: Input matrices A, B, C_initial are FP16 type for the problem)
Matrix A (M=2,K=3): [1.04.0​2.05.0​3.06.0​] Matrix B (K=3,N=2): ​1.03.05.0​2.04.06.0​​ Matrix Cinitial​ (M=2,N=2): [1.01.0​1.01.0​] α=1.0 (FP32) β=0.0 (FP32) Output (FP16):
Matrix C (M=2,N=2): [22.049.0​28.064.0​]

Constraints

  • 16 ≤ M, N, K ≤ 4096
  • Performance is measured with K = 1,024, M = 1,024, N = 1,024

Starter code (CUDA)

#include <cuda_fp16.h>
#include <cuda_runtime.h>

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

Solve it on your GPU

Previous: ReLUNext: Leaky ReLU

From LeetGPU, CC BY-NC-ND 4.0.