#!POPCORN leaderboard amd-fp8-mm 
#!POPCORN GPU MI300
# This script provides a template for using load_inline to run a HIP kernel for
from torch.utils.cpp_extension import load_inline
from torch.profiler import profile, record_function, ProfilerActivity
from task import input_t, output_t
CPP_WRAPPER = """
void fp8_mm(torch::Tensor a, torch::Tensor b, torch::Tensor as, torch::Tensor bs, torch::Tensor c);
"""

CUDA_SRC = """
#include <hip/amd_detail/amd_hip_fp8.h>
#include <hip/amd_detail/amd_hip_bf16.h>

constexpr const int BLOCK = 32;  // Increased block size for MI300X
constexpr const int COARSENING = 2; // increase coarsening to reduce thread sequential processing

__global__ void custom_kernel(const __hip_fp8_e4m3_fnuz* a, const __hip_fp8_e4m3_fnuz* b, const float* as, const float* bs, 
                   __hip_bfloat16* c, const uint M, const uint N, const uint K) {

    // converting 1D block Dim to 2D block Dim

    const uint tcol = threadIdx.x % BLOCK;
    const uint trow = threadIdx.x / BLOCK;

    const uint cx  = BLOCK * blockIdx.x + trow ;
    const uint cy = BLOCK * blockIdx.y + tcol ;
    

    __shared__ __hip_fp8_e4m3_fnuz shared_a[BLOCK * BLOCK];
    __shared__ __hip_fp8_e4m3_fnuz shared_b[BLOCK * BLOCK];
    
    // loadi a, b, as, bs
    
    // TODO: convert this return to proper if to enter the execution
    if(cx < M && cy < N) {
        float result = 0;

        //int next = 1;
        //int current = 0;

        for (int k = 0; k < K / BLOCK; ++k) {
            
            float block_result = 0;
            // (to access base pointer of this block) + (accessing specific tile of the block) + ( to access the specific value inside this tile)

            const float scale = as[ (((k * BLOCK) / 128) * M) + cx ] *  bs[  ((k * BLOCK) /128)  * ((N + 128 - 1) / 128) + ( cy/128 ) ];


            // (block_ptr) + (kth tile pointer ) + (col,trow) value to load : here we load (col, trow) for memory coalescing
            // due to column major matrixs a & b.
            shared_a[ BLOCK * trow +  tcol  ] = a[ ( blockIdx.x * BLOCK ) + ( k * BLOCK * M ) + ( tcol  + M *  trow )];
            shared_b[ BLOCK * trow  + tcol  ] = b[ ( blockIdx.y * BLOCK ) + ( k * BLOCK * N )+ (   tcol+ N * trow )];
            
            __syncthreads();

            #pragma unroll 8
            for(int ii = 0; ii < BLOCK; ++ii){

                block_result += (float)shared_a[BLOCK * ii + trow ] * (float)shared_b[BLOCK * ii + tcol]; 
            }
            
            result += block_result * scale ;

            //current ^= 1;
            //next ^= 1;
            __syncthreads();

        }
    
        c[cx * N  + cy] = (__hip_bfloat16)result;
    
    }
}

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);
    
    // Optimized grid and block dimensions for MI300X
    dim3 block(BLOCK * BLOCK);  // 1024 threads per block
    
    dim3 grid((m + BLOCK - 1) / BLOCK, (n + BLOCK - 1) / BLOCK);
    
    custom_kernel<<<grid, block, 0, 0>>>(
        (__hip_fp8_e4m3_fnuz*)a.data_ptr(),
        (__hip_fp8_e4m3_fnuz*)b.data_ptr(),
        as.data_ptr<float>(),
        bs.data_ptr<float>(),
        (__hip_bfloat16*)c.data_ptr(),
        m, n, k
    );
}
"""


import os
os.environ["CXX"] = "clang++"

module = 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"],
)

def custom_kernel(data: input_t) -> output_t:
    a, b, a_scale, b_scale, c = data
    # with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
    module.fp8_mm(a, b, a_scale, b_scale, c)
    # prof.export_chrome_trace("resnet18_profile.json")

    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 -std=c++20 -fno-gpu-rdc -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 test /tmp/tmphm0fuyzk
[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.
