#!POPCORN leaderboard amd-fp8-mm
from torch.utils.cpp_extension import load_inline
from task import input_t, output_t
import sys

import os
if "PYTORCH_ROCM_ARCH" not in os.environ:
    os.environ["PYTORCH_ROCM_ARCH"] = "gfx942:xnack-"

CPP_WRAPPER = """
void fp8_mm(torch::Tensor a, torch::Tensor b, torch::Tensor as, torch::Tensor bs, torch::Tensor c);
"""

CUDA_SRC = """
#include <hip/hip_runtime.h>
#include <hip/amd_detail/amd_hip_fp8.h>
#include <hip/amd_detail/amd_hip_bf16.h>
#include <hip/hip_cooperative_groups.h>
#include <rocwmma/rocwmma.hpp>
namespace cg = cooperative_groups;

#define K_JUMP 128
#define WMMA_M 32
#define WMMA_N 32
#define WMMA_K 16
#define NUM_WARP_X 4
#define NUM_WARP_Y 4
#define WARP_SIZE 64
#define WMMA_PLACEHOLDER 4

__global__ void __launch_bounds__(1024, 8) custom_kernel(const __hip_fp8_e4m3_fnuz* A_ptr, const __hip_fp8_e4m3_fnuz* B_ptr, const float* As_ptr, const float* Bs_ptr, rocwmma::bfloat16_t* C_ptr, int M, int N, int K) {
    /*
    a block covers 32x32 elem
    dim3 block_size(64, 1) -> 1 thread calculates 16 elem

    Perform B @ A.T = C.T, so we can store scale As in a VGPR of each thread in a warp
    B: NxK col-maj -- Bs (128x128 scaling): N/128 x K/128 col-maj
    A.T: KxM row-maj -- As (1x128 scaling): K/ 128 x M row-maj
    C.T: NxM col-maj
    
    M, N, K are divisible by 128

    Kernel to use when M, N is balanced
    Use wmma 32x32x16

    tileB[128][128]
    tileA[128][112]

    SMEM usage per block: 32KB

    */  

    int sn = (N + 128 - 1) / 128;

    __shared__ __hip_fp8_e4m3_fnuz tileB[128][136]; // col-maj = row-maj transposed 
    __shared__ __hip_fp8_e4m3_fnuz tileA[128][120]; // row-maj
    int ldb = 136;
    int lda = 120;

    auto frag_acc_master = rocwmma::fragment<rocwmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float>();
    rocwmma::fill_fragment(frag_acc_master, 0.f);

    cg::thread_block this_tb = cg::this_thread_block();
    auto group64 = cg::tiled_partition<64>(this_tb); // 1024 threads -> 64 x 16
    int t64x = group64.thread_rank();
    int t64y = group64.meta_group_rank(); 

    for (int kbase = 0; kbase < K; kbase += K_JUMP) {
        int warp_idx_y = threadIdx.y;    
        int warp_idx_x = threadIdx.x / WARP_SIZE;  

        int col_base_C = (blockIdx.x * NUM_WARP_X + warp_idx_x) * WMMA_N; 
        int row_base_C = (blockIdx.y * NUM_WARP_Y + warp_idx_y) * WMMA_M;  
        // -----------------------------------------------------------------------------

        // TODO: replace += 16 with += group64.meta_group_size()

        #pragma unroll
        for (int kmini = 0; kmini < K_JUMP - 16; kmini += 16){ // 16 is num group
            tileA[t64x][kmini + t64y] = A_ptr[blockIdx.x * WMMA_M * NUM_WARP_X + t64x + M * (kbase + kmini + t64y)];
            tileA[t64x + 64][kmini + t64y] = A_ptr[blockIdx.x * WMMA_M * NUM_WARP_X + t64x + 64 + M * (kbase + kmini + t64y)];
            tileB[t64x][kmini + t64y] = B_ptr[(kbase + kmini + t64y) * N + blockIdx.y * WMMA_N * NUM_WARP_Y + t64x];
            tileB[t64x + 64][kmini + t64y] = B_ptr[(kbase + kmini + t64y) * N + blockIdx.y * WMMA_N * NUM_WARP_Y + t64x + 64];            
        }

        tileB[t64x][112 + t64y] = B_ptr[(kbase + 112 + t64y) * N + blockIdx.y * WMMA_N * NUM_WARP_Y + t64x];
        tileB[t64x + 64][112 + t64y] = B_ptr[(kbase + 112 + t64y) * N + blockIdx.y * WMMA_N * NUM_WARP_Y + t64x + 64];

        float tileAs = As_ptr[(kbase / 128) * M + col_base_C + t64x % WMMA_N];
        float tileBs = Bs_ptr[(kbase / 128) * sn + (blockIdx.y * NUM_WARP_Y * WMMA_M) / 128];
        float scale = tileAs * tileBs;

        // float scale = tileAs * tileBs; // this gives large error, due to non-associative of IEEE 754 ?
        __syncthreads();

        // MFMA

        // MFMA on SMEM
        auto frag_acc_block = rocwmma::fragment<rocwmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float>() ;
        rocwmma::fill_fragment(frag_acc_block, 0.f);

        auto frag_a = rocwmma::fragment<rocwmma::matrix_a, WMMA_M, WMMA_N, WMMA_K, __hip_fp8_e4m3_fnuz, rocwmma::row_major>();
        auto frag_b = rocwmma::fragment<rocwmma::matrix_b, WMMA_M, WMMA_N, WMMA_K, __hip_fp8_e4m3_fnuz, rocwmma::col_major>();

  

        #pragma unroll 1
        for (int kmini = 0; kmini < K_JUMP - 16; kmini += WMMA_K) {
            rocwmma::load_matrix_sync(frag_a, &tileB[0][0] + (warp_idx_y * WMMA_M) * ldb + kmini, ldb);            
            rocwmma::load_matrix_sync(frag_b, &tileA[0][0] + kmini + lda * (warp_idx_x * WMMA_N), lda);
            rocwmma::mma_sync(frag_acc_block, frag_a, frag_b, frag_acc_block);                                
        }

        // ---------------------------------- LEFT OVER -------------------------------------------
        // left over 32 rows
  
        auto frag_b_left = rocwmma::fragment<rocwmma::matrix_b, WMMA_M, WMMA_N, WMMA_K, __hip_fp8_e4m3_fnuz, rocwmma::row_major>(); 
        rocwmma::load_matrix_sync(frag_b_left, A_ptr + (kbase + 112) * M + col_base_C, M);

        // auto transposed_frag = rocwmma::applyTranspose(frag_b_left);     
        rocwmma::load_matrix_sync(frag_a, &tileB[0][0] + (warp_idx_y * WMMA_M) * ldb + 112, ldb);            

        rocwmma::mma_sync(frag_acc_block, frag_a, frag_b_left, frag_acc_block);                                




        __syncthreads();
        // Mult scalers

        // TODO: use frag_acc_master.num_elements or 4 to reduce register pressure
        #pragma unroll
        for (int i = 0; i < frag_acc_master.num_elements; ++i){
            // frag_acc_master.x[i] += tileAs * frag_acc_block.x[i] * tileBs;
            // frag_acc_master.x[i] = fmaf(tileAs * frag_acc_block.x[i], tileBs, frag_acc_master.x[i]);
            frag_acc_master.x[i] = fmaf(scale, frag_acc_block.x[i], frag_acc_master.x[i]);
        }
    
        // __syncthreads();

    }// end for (int kbase = 0; kbase < K; kbase += 128) 
    int warp_idx_y = threadIdx.y;
    int row_base_C = (blockIdx.y * NUM_WARP_Y + warp_idx_y) * WMMA_M;
    if (row_base_C >= N) return;

    int warp_idx_x = threadIdx.x / WARP_SIZE;    
    int col_base_C = (blockIdx.x * NUM_WARP_X + warp_idx_x) * WMMA_N;
    if (col_base_C >= M) return;    
    
    // Convert fp32 to bf16 and store
    // TODO: change WMMA_PLACEHOLDER from 8 to 16
    auto frag_result = rocwmma::fragment<rocwmma::accumulator, WMMA_M, WMMA_N, WMMA_PLACEHOLDER, rocwmma::bfloat16_t>(); //Placeholder frag
    
    #pragma unroll
    for (int i = 0; i < frag_acc_master.num_elements; ++i) {
        frag_result.x[i] = (rocwmma::bfloat16_t)frag_acc_master.x[i];
    }
    
    rocwmma::store_matrix_sync(C_ptr + row_base_C + N * col_base_C, frag_result, N, rocwmma::mem_col_major);

}

void fp8_mm(torch::Tensor a, torch::Tensor b, torch::Tensor as, torch::Tensor bs, torch::Tensor c) {
    int M = a.size(0);
    int N = b.size(0);
    int K = a.size(1);

    int num_warp_x = NUM_WARP_X;
    int num_warp_y = NUM_WARP_Y;
    dim3 block_size((WARP_SIZE * num_warp_x), num_warp_y);
    // dim3 grid_size(M / (num_warp_x * WMMA_N), N / (num_warp_y * WMMA_M));
    dim3 grid_size((M + num_warp_x * WMMA_N - 1) / (num_warp_x * WMMA_N), 
                   (N + num_warp_y * WMMA_M - 1) / (num_warp_y * WMMA_M));
    custom_kernel<<<grid_size, block_size, 0, 0>>> ((__hip_fp8_e4m3_fnuz*)a.data_ptr(), (__hip_fp8_e4m3_fnuz*)b.data_ptr(), 
    as.data_ptr<float>(), bs.data_ptr<float>(), (rocwmma::bfloat16_t*)c.data_ptr(), M, N, K);
    //C10_CUDA_CHECK(cudaGetLastError());
}
"""

import os
os.environ["CXX"] = "clang++"
import torch
block_shape = 128


# big one, used when N is >= 3072
module_big = load_inline(
    name='fp8_mm',
    cpp_sources=[CPP_WRAPPER],
    cuda_sources=[CUDA_SRC],
    functions=['fp8_mm'],
    verbose=True,
    # extra_cuda_cflags=["--offload-arch=gfx942", "-std=c++20", "-O2", "-Rpass-analysis=kernel-resource-usage"],
    extra_cuda_cflags=["-std=c++20", "-ffast-math"],    
    # extra_cuda_cflags=["--offload-arch=gfx942", "-std=c++20"],
)

def custom_kernel(data: input_t) -> output_t:
    a, b, a_scale, b_scale, c = data

    # m = a.shape[0]
    # n = b.shape[0]
    # k = a.shape[1]

    module_big.fp8_mm(a, b, a_scale, b_scale, c)  
    return c

python submission.py
[92mSuccessfully preprocessed all matching files.[0m

/home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/main.cpp -> /home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/main.cpp [skipped, no changes]
/home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/cuda.cu -> /home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/hip.hip [ok]
Total number of unsupported CUDA function calls: 0


Total number of replaced kernel launches: 1
[1/3] clang++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=fp8_mm -DTORCH_API_INCLUDE_EXTENSION_H -DPYBIND11_COMPILER_TYPE=\"_gcc\" -DPYBIND11_STDLIB=\"_libstdcpp\" -DPYBIND11_BUILD_ABI=\"_cxxabi1016\" -isystem /usr/local/lib/python3.10/dist-packages/torch/include -isystem /usr/local/lib/python3.10/dist-packages/torch/include/torch/csrc/api/include -isystem /usr/local/lib/python3.10/dist-packages/torch/include/THH -isystem /opt/rocm-6.3.1/include -isystem /usr/include/python3.10 -fPIC -std=c++17 -c /home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/main.cpp -o main.o -D__HIP_PLATFORM_AMD__=1 -DUSE_ROCM=1 -DHIPBLAS_V2 -fPIC
[2/3] /opt/rocm-6.3.1/bin/hipcc  -DWITH_HIP -DTORCH_EXTENSION_NAME=fp8_mm -DTORCH_API_INCLUDE_EXTENSION_H -DPYBIND11_COMPILER_TYPE=\"_gcc\" -DPYBIND11_STDLIB=\"_libstdcpp\" -DPYBIND11_BUILD_ABI=\"_cxxabi1016\" -isystem /usr/local/lib/python3.10/dist-packages/torch/include -isystem /usr/local/lib/python3.10/dist-packages/torch/include/torch/csrc/api/include -isystem /usr/local/lib/python3.10/dist-packages/torch/include/THH -isystem /opt/rocm-6.3.1/include -isystem /usr/include/python3.10 -fPIC -std=c++17 -D__HIP_PLATFORM_AMD__=1 -DUSE_ROCM=1 -DHIPBLAS_V2 -fPIC -DCUDA_HAS_FP16=1 -D__HIP_NO_HALF_OPERATORS__=1 -D__HIP_NO_HALF_CONVERSIONS__=1 -DHIP_ENABLE_WARP_SYNC_BUILTINS=1 --offload-arch=gfx942:xnack- -fno-gpu-rdc -std=c++20 -ffast-math -c /home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/hip.hip -o hip.cuda.o 
[3/3] clang++ main.o hip.cuda.o -shared -L/usr/local/lib/python3.10/dist-packages/torch/lib -lc10 -lc10_hip -ltorch_cpu -ltorch_hip -ltorch -ltorch_python -L/opt/rocm-6.3.1/lib -lamdhip64 -o fp8_mm.so

python eval.py benchmark /tmp/tmpz891b6nn
[92mSuccessfully preprocessed all matching files.[0m

/home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/main.cpp -> /home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/main.cpp [skipped, no changes]
/home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/cuda.cu -> /home/runner/.cache/torch_extensions/py310_cpu/fp8_mm/hip.hip [skipped, already hipified]
Total number of unsupported CUDA function calls: 0


Total number of replaced kernel launches: 1
ninja: no work to do.
