#!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 2
#define NUM_WARP_Y 2
#define WARP_SIZE 64

__global__ void 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
    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

    A: M x K col-maj --- As (1x128 scaling): M x K/128 col-maj
    B: K x N row-maj --- Bs (128x128 scaling): K/128 x N/128 row-maj
    C: M x N row-maj
    M, N, K are divisible by 128
    */  
    using floatx16 = __attribute__((__vector_size__(16 * sizeof(float)))) float;

    // int warp_idx_x = threadIdx.x / WARP_SIZE; 
    // int warp_idx_y = threadIdx.y;
    // 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;
    int sn = (N + 128 - 1) / 128;

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

    floatx16 accum = {0.f}; // Each thread computes 16 elements
        
    cg::thread_block this_tb = cg::this_thread_block();
    auto group64 = cg::tiled_partition<64>(this_tb); // 256 threads -> 64 x 4
    int t64x = group64.thread_rank();
    int t64y = group64.meta_group_rank(); 

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

        __syncthreads();

        // MFMA

        floatx16 temp_accum = {0.f};
        int warp_idx_x = threadIdx.x / WARP_SIZE; 
        int warp_idx_y = threadIdx.y;

        #pragma unroll 2
        for (int kmini = 0; kmini < 128; kmini += WMMA_K) {
                // Load frags

                long a_frag;
                int tileA_row = warp_idx_y * WMMA_M + t64x % 32;
                int tileA_col = kmini + (t64x / 32) * 8;
                a_frag = *reinterpret_cast<long*>(&tileB[0][0] + tileA_row * 136 + tileA_col);
                
                long b_frag;
                int tileB_row = kmini + (t64x / 32) * 8;
                int tileB_col = warp_idx_x * WMMA_N + t64x % 32;
                b_frag = *reinterpret_cast<long*>(&tileA[0][0] + tileB_col * 136 + tileB_row);
                                    
                // MFMA instrinsic
                temp_accum = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(a_frag, b_frag, temp_accum, 0, 0, 0);           
        }
        int col_base_C = (blockIdx.x * NUM_WARP_X + warp_idx_x) * WMMA_N;
        int row_base_C = (blockIdx.y * NUM_WARP_Y) * WMMA_M;        
        // Mult scalers
        float tileAs = As_ptr[(kbase / 128) * M + col_base_C + t64x % WMMA_N];
        float tileBs = Bs_ptr[(kbase / 128) * sn + row_base_C / 128];
        float scale = tileAs * tileBs;

        #pragma unroll
        for (int i = 0; i < 16; ++i){
            accum[i] = fmaf(scale, temp_accum[i], accum[i]);
        }        

        __syncthreads();

    }// end for (int kbase = 0; kbase < K; kbase += 128) 

    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;

    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;



    // Store accum to GMEM
    int col = N * (col_base_C + (t64x % 32));
    int base_row = row_base_C + 4 * (t64x / 32);
    
    C_ptr[base_row + 8 * 0 + 0 + col] = accum[0];
    C_ptr[base_row + 8 * 0 + 1 + col] = accum[1];
    C_ptr[base_row + 8 * 0 + 2 + col] = accum[2];
    C_ptr[base_row + 8 * 0 + 3 + col] = accum[3];
    
    C_ptr[base_row + 8 * 1 + 0 + col] = accum[4];
    C_ptr[base_row + 8 * 1 + 1 + col] = accum[5];
    C_ptr[base_row + 8 * 1 + 2 + col] = accum[6];
    C_ptr[base_row + 8 * 1 + 3 + col] = accum[7];
    
    C_ptr[base_row + 8 * 2 + 0 + col] = accum[8];
    C_ptr[base_row + 8 * 2 + 1 + col] = accum[9];
    C_ptr[base_row + 8 * 2 + 2 + col] = accum[10];
    C_ptr[base_row + 8 * 2 + 3 + col] = accum[11];
    
    C_ptr[base_row + 8 * 3 + 0 + col] = accum[12];
    C_ptr[base_row + 8 * 3 + 1 + col] = accum[13];
    C_ptr[base_row + 8 * 3 + 2 + col] = accum[14];
    C_ptr[base_row + 8 * 3 + 3 + col] = accum[15];
}

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

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 -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/tmpaf7xlw38
[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.
