#!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
#define OPTION 0


__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: 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 is divisible by 128
    K is divisible by 128
    18.5 KD of LDS
    */
    
    __shared__ __hip_fp8_e4m3_fnuz tileA[4][8][512]; // row-major
    __shared__ __hip_fp8_e4m3_fnuz tileB[4][8][512]; // col-major, = row-major transposed
    // __shared__ __hip_fp8_e4m3_fnuz tileB[128][72]; // col-major, = row-major transposed
    int lda = 512;
    int ldb = 512;
    __shared__ float tileAs[128];
    auto frag_acc_master = rocwmma::fragment<rocwmma::accumulator, WMMA_M, WMMA_N, WMMA_K, float>();
    rocwmma::fill_fragment(frag_acc_master, 0.f);

    // int lda = M;
    // int ldb = N;
    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(); 

    int col_512_idx = (t64y / 8) * 256 + (t64x % 32) * 8 + t64y % 8;
    int MN_load_idx = t64x % 32 + 32 * (t64x / 32);    

    for (int kbase = 0; kbase < K; kbase += K_JUMP) {

        // Load SMEM: tileA, tileB, tileAs, tileBs
        // TRY: test tiled partition 64

        // ----------------------------- FIRST HALF --------------------------
        int K_load_idx = kbase + t64y % 8 + 8 * (t64y / 8);
        // int col_512_idx = (t64y / 8) * 256 + (t64x % 32) * 8 + t64y % 8;
        // int MN_load_idx = t64x % 32 + 32 * (t64x / 32);
        #pragma unroll
        for (int kblockidx = 0; kblockidx < 8; ++kblockidx) {
            #pragma unroll
            for (int i = 0; i < 2; ++i) { // top and bottom
                int offset = i * 64;
                
                tileA[i * 2 + t64x / 32][kblockidx][col_512_idx] = 
                    A_ptr[offset + blockIdx.y * WMMA_M * NUM_WARP_Y + MN_load_idx + M * (K_load_idx + kblockidx * 16)];
        
                tileB[i * 2 + t64x / 32][kblockidx][col_512_idx] = 
                    B_ptr[offset + blockIdx.x * WMMA_N * NUM_WARP_X + MN_load_idx + N * (K_load_idx + kblockidx * 16)];
            }
        }
        
       
        __syncthreads();

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

        // int warp_idx_y = threadIdx.y;
        // int warp_idx_x = threadIdx.x / WARP_SIZE;

        int warp_idx_x = threadIdx.x / WARP_SIZE;    
        int warp_idx_y = threadIdx.y;

        #pragma unroll 2
        for (int kblockidx = 0; kblockidx < 8; ++kblockidx) {
            memcpy(&frag_a.x[0], &tileA[warp_idx_y][kblockidx][t64x * 8], sizeof(long));
            memcpy(&frag_b.x[0], &tileB[warp_idx_x][kblockidx][t64x * 8], sizeof(long));
            rocwmma::mma_sync(frag_acc_block, frag_a, frag_b, frag_acc_block);
        } // end for kmini

        int sn = (N + 128 - 1) / 128; 
        float tileBs = Bs_ptr[(kbase / 128) * sn + ((blockIdx.x * NUM_WARP_X * WMMA_N) / 128)];
        int row_base_C = (blockIdx.y * NUM_WARP_Y + warp_idx_y) * WMMA_M;
        #pragma unroll
        for (int i = 0; i < 4; ++i){
            #pragma unroll
            for (int j = 0; j < 4; ++j){
                // C_ptr[(row_base_C + 8 * i + 4 * (t64x / 32) + j) * N + col_base_C + (t64x % 32)] = accum[i * 4 + j];
                frag_acc_master.x[i * 4 + j] += As_ptr[row_base_C + 4 * (t64x / 32) + 8 * i + j + M * (kbase / 128)] * frag_acc_block.x[i * 4 + j] * tileBs;
            }
        }

        // #pragma unroll
        // for (int i = 0; i < 4; ++i){
        //     #pragma unroll
        //     for (int j = 0; j < 4; ++j){
        //         frag_acc_master.x[i * 4 + j] += tileAs[warp_idx_y * WMMA_M + 4 * (t64x / 32) + 8 * i + j] * frag_acc_block.x[i * 4 + j];
        //     }
        // }  

        __syncthreads(); // We need this synthreads()
    } // end for kbase

    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 >= N) 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 >= M) return;

    // Convert fp32 to bf16 and store
    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];
    }

    //int warp_idx_x = threadIdx.x / WARP_SIZE;    
    //int col_base_C = (blockIdx.x * NUM_WARP_X + warp_idx_x) * WMMA_N;  

    //int warp_idx_y = threadIdx.y;
    //int row_base_C = (blockIdx.y * NUM_WARP_Y + warp_idx_y) * WMMA_M;
      
    rocwmma::store_matrix_sync(C_ptr + row_base_C * N + col_base_C, frag_result, N, rocwmma::mem_row_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((N + num_warp_x * WMMA_N - 1) / (num_warp_x * WMMA_N), 
                   (M + 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=["-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/tmp57ngd2dw
[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.
