#!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 256
#define WMMA_M 16
#define WMMA_N 16
#define WMMA_K 32
#define NUM_WARP_X 4
#define NUM_WARP_Y 4
#define WARP_SIZE 64
#define WMMA_PLACEHOLDER 8

__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) {
    /*
    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 are divisible by 64, K is divisible by 256

    SMEM per block: 32 KB

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

    __shared__ __hip_fp8_e4m3_fnuz tileA[64][256]; // col-maj = row-maj transposed 
    __shared__ __hip_fp8_e4m3_fnuz tileB[64][256]; // row-maj

    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();

    for (int kbase = 0; kbase < K; kbase += K_JUMP) {
        int warp_idx_y = threadIdx.y;
        int row_base_C = (blockIdx.y * NUM_WARP_Y + warp_idx_y) * WMMA_M;
    
        int warp_idx_x = threadIdx.x / WARP_SIZE;    
        int col_base_C = (blockIdx.x * NUM_WARP_X + warp_idx_x) * WMMA_N;

        int t64x = this_tb.thread_rank() % 64;
        int t64y = this_tb.thread_rank() / 64;

        #pragma unroll 4
        for (int kmini = 0; kmini < 128; kmini += 16){ // 16 is num group
            int K_idx_shifty = (kmini + t64y + 8 * (t64x % 16)) % 128;            

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

        float tileAs1 = As_ptr[(kbase / 128) * M + col_base_C + t64x % WMMA_N];
        float tileBs1 = Bs_ptr[(kbase / 128) * sn + (blockIdx.y * NUM_WARP_Y * WMMA_M) / 128];
        float scale1 = tileAs1 * tileBs1;
        float tileAs2 = As_ptr[(1 + kbase / 128) * M + col_base_C + t64x % WMMA_N];
        float tileBs2 = Bs_ptr[(1 + kbase / 128) * sn + (blockIdx.y * NUM_WARP_Y * WMMA_M) / 128];
        float scale2 = tileAs2 * tileBs2;

        __syncthreads(); 
        // __threadfence_block();
        // 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
        for (int kmini = 0; kmini < 128; kmini += WMMA_K){
            int tileB_row = warp_idx_y * WMMA_M + t64x % 16;
            int K_idx_base = kmini + (t64x / 16) * 8;
            int K_idx_shiftyB = (K_idx_base + 8 * tileB_row) % 128;
            // memcpy(&frag_a.x[0], &tileB[tileB_row][K_idx_shiftyB], sizeof(long));
            memcpy(&frag_a.x[0], &tileB[0][0] + tileB_row * 256 + K_idx_shiftyB, sizeof(long)); 

            int tileA_col = warp_idx_x * WMMA_N + t64x % 16;
            // int K_idx_shiftyA = (K_idx_base + 8 * tileA_col) % 128;
            // memcpy(&frag_b.x[0], &tileA[tileA_col][K_idx_shiftyB], sizeof(long));
            memcpy(&frag_b.x[0], &tileA[0][0] + tileA_col * 256 + K_idx_shiftyB, sizeof(long));
            rocwmma::mma_sync(frag_acc_block, frag_a, frag_b, frag_acc_block);
        }


        // Mult scalers
        #pragma unroll
        for (int i = 0; i < frag_acc_master.num_elements; ++i){
            frag_acc_master.x[i] = fmaf(scale1, frag_acc_block.x[i], frag_acc_master.x[i]);            
        }

        rocwmma::fill_fragment(frag_acc_block, 0.f);

        #pragma unroll
        for (int kmini = 0; kmini < 128; kmini += WMMA_K){
            int tileB_row = warp_idx_y * WMMA_M + t64x % 16;
            int K_idx_base = kmini + (t64x / 16) * 8;
            int K_idx_shiftyB = (K_idx_base + 8 * tileB_row) % 128;
            // memcpy(&frag_a.x[0], &tileB[tileB_row][128 + K_idx_shiftyB], sizeof(long));
            memcpy(&frag_a.x[0], &tileB[0][0] + tileB_row * 256 + 128 + K_idx_shiftyB, sizeof(long)); 

            int tileA_col = warp_idx_x * WMMA_N + t64x % 16;
            // int K_idx_shiftyA = (K_idx_base + 8 * tileA_col) % 128;
            // memcpy(&frag_b.x[0], &tileA[tileA_col][128 + K_idx_shiftyB], sizeof(long));
            memcpy(&frag_b.x[0], &tileA[0][0] + tileA_col * 256 + 128 + K_idx_shiftyB, sizeof(long));

            rocwmma::mma_sync(frag_acc_block, frag_a, frag_b, frag_acc_block);
        } 



        // Mult scalers
        #pragma unroll
        for (int i = 0; i < frag_acc_master.num_elements; ++i){
            frag_acc_master.x[i] = fmaf(scale2, 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 - 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", "-ffast-math"],
    extra_cuda_cflags=["-std=c++20", "-ffast-math"],    
)

def custom_kernel(data: input_t) -> output_t:
    a, b, a_scale, b_scale, c = data
    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++ hip.cuda.o main.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/tmpfok82ou8
[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.
