Triton Tiled Matrix Multiplication
Problem Statement
Implement a tiled matrix multiplication C = A @ B where A is (M, K) and B is (K, N), using a 2D launch grid and an accumulator.
Background
Each program computes one BLOCK_M x BLOCK_N output tile. Loop over K in steps of BLOCK_K, loading tiles of A and B, multiplying with tl.dot, and accumulating into a float32 register tile. Strides let the kernel work on any contiguous layout; masks handle non-tile-multiple sizes.
Your Task
Implement matmul_kernel and run(M=128, N=128, K=128) comparing to A @ B.
How it is tested
Your solution must define a top-level function run(...) that allocates inputs on the GPU, launches your Triton kernel, and returns a boolean from torch.allclose(triton_out, torch_reference, ...). The grader prints run(...); the expected output is True.
Example
M = 128, N = 128, K = 128
True
- The input values
M = 128,N = 128, andK = 128are used to allocate matricesAandBwith shapes(M, K)and(K, N)respectively. - The
matmul_kernelfunction is launched with a 2D grid to compute the matrix productC = A @ Bin a tiled manner, using blocks of sizeBLOCK_M x BLOCK_Nand accumulating results in a float32 register tile. - The tiled matrix multiplication is performed by looping over
Kin steps ofBLOCK_K, loading tiles ofAandB, and multiplying them usingtl.dot, with masks handling non-tile-multiple sizes. - The resulting matrix
Cfrom the Triton kernel is compared to the reference result fromtorchusingtorch.allclose, which checks if the two matrices are element-wise equal within a certain tolerance, resulting in the outputTrue.
Constraints
- 2D grid: (cdiv(M, BLOCK_M), cdiv(N, BLOCK_N))
- Accumulate in a tl.float32 register tile, loop over K by BLOCK_K
- Use tl.dot and mask all loads/stores; pass strides