|
| 1 | +using PythonCall, Reactant, Test |
| 2 | + |
| 3 | +pyimport("sys").path.append(@__DIR__) |
| 4 | + |
| 5 | +matmul_kernel = pyimport("matmul").matmul_kernel |
| 6 | + |
| 7 | +const RunningOnCUDA = contains(string(Reactant.devices()[1]), "CUDA") |
| 8 | + |
| 9 | +function matmul_triton(a::AbstractMatrix{T}, b::AbstractMatrix{T}) where {T} |
| 10 | + # a: [M, K] --> aᵀ: [K, M] |
| 11 | + # b: [K, N] --> bᵀ: [N, K] |
| 12 | + # c: a × b [M, N] --> cᵀ: bᵀ × aᵀ [N, M] |
| 13 | + a_transposed = permutedims(a, (2, 1)) # match python array layout |
| 14 | + b_transposed = permutedims(b, (2, 1)) # match python array layout |
| 15 | + @assert size(b_transposed, 2) == size(a_transposed, 1) "Inner dimensions must match \ |
| 16 | + for matmul" |
| 17 | + M, K = size(b_transposed) |
| 18 | + K, N = size(a_transposed) |
| 19 | + |
| 20 | + out = similar(a_transposed, T, M, N) # cᵀ |
| 21 | + |
| 22 | + matmul_kernel( |
| 23 | + b_transposed, |
| 24 | + a_transposed, |
| 25 | + out, |
| 26 | + M, |
| 27 | + N, |
| 28 | + K, |
| 29 | + Reactant.rowmajor_stride(b_transposed, 1), |
| 30 | + Reactant.rowmajor_stride(b_transposed, 2), |
| 31 | + Reactant.rowmajor_stride(a_transposed, 1), |
| 32 | + Reactant.rowmajor_stride(a_transposed, 2), |
| 33 | + Reactant.rowmajor_stride(out, 1), |
| 34 | + Reactant.rowmajor_stride(out, 2), |
| 35 | + 64, |
| 36 | + 256, |
| 37 | + 32, |
| 38 | + 8; |
| 39 | + grid=(cld(M, 64) * cld(N, 256),), |
| 40 | + num_stages=4, |
| 41 | + num_warps=4, |
| 42 | + ) |
| 43 | + |
| 44 | + return permutedims(out, (2, 1)) |
| 45 | +end |
| 46 | + |
| 47 | +@testset "matmul" begin |
| 48 | + if RunningOnCUDA |
| 49 | + @testset for M in (4, 32, 256, 1024), |
| 50 | + K in (4, 32, 512, 2048), |
| 51 | + N in (4, 32, 256, 1024) |
| 52 | + |
| 53 | + a = Reactant.to_rarray(rand(Float32, M, K)) |
| 54 | + b = Reactant.to_rarray(rand(Float32, K, N)) |
| 55 | + |
| 56 | + # XXX: shared_memory???? |
| 57 | + # XXX: seems to work correctly for small matrices |
| 58 | + @test_broken @jit(matmul_triton(a, b)) ≈ @jit(a * b) |
| 59 | + end |
| 60 | + end |
| 61 | +end |
0 commit comments