# This script provides a template for using load_inline to run a HIP kernel for
from torch.utils.cpp_extension import load_inline
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>

using f32x16 = __attribute__( (__vector_size__(16 * sizeof(float)) )) float;

constexpr const int BLOCK = 128;

struct input_t
{
    uint64_t regs[8][128];
    union 
    {
        float weight[64];
        uint64_t weight_data[8][4];
    };

};

__device__ static uint64_t pack_u16x8_to_u64(const uint16_t* src)
{
    uint16_t dst[] = { src[1], src[3], src[5], src[7] };
    return *reinterpret_cast<uint64_t*>(dst);
}

__global__ void custom_kernel(const input_t* cache, __hip_bfloat16* c, int m, int n, int k, int col, int offset) {
    const input_t* a = cache + blockIdx.x * col;
    const input_t* b = cache + blockIdx.y * col + offset;
    int fx = threadIdx.x >> 6 & 1;
    int fy = threadIdx.x >> 7 & 1;
    int cx = 32 * (2 * blockIdx.x | fx);
    int cy = 32 * (2 * blockIdx.y | fy);
    if(cx >= m || cy >= n) return;
    int tx = threadIdx.x & 31;
    int ty = threadIdx.x >> 5 & 1;
    const int idx = (threadIdx.x & 127);
    const int idy = (threadIdx.x & 63) | (fy << 6);
    f32x16 result = { };
    for(int i = 0; i < (k + 127) >> 7; ++i) {
        const auto& ap = a[i];
        const auto& bp = b[i];
        f32x16 block_result = { };
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[0][idy], ap.regs[0][idx], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[1][idy], ap.regs[1][idx], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[2][idy], ap.regs[2][idx], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[3][idy], ap.regs[3][idx], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[4][idy], ap.regs[4][idx], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[5][idy], ap.regs[5][idx], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[6][idy], ap.regs[6][idx], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp.regs[7][idy], ap.regs[7][idx], block_result, 0, 0, 0);
        result += block_result * bp.weight[0] * ap.weight[fx << 5 | tx];
    }
    const auto* src = reinterpret_cast<const uint16_t(*)[8]>(&result);
    uint64_t* dst = reinterpret_cast<uint64_t*>(c + (tx + cx) * n + cy + ty * 4);
    dst[0] = pack_u16x8_to_u64(src[0]);
    dst[2] = pack_u16x8_to_u64(src[1]);
    dst[4] = pack_u16x8_to_u64(src[2]);
    dst[6] = pack_u16x8_to_u64(src[3]);
}

__global__ void reorder_kernel(const __hip_fp8_e4m3_fnuz* src, const __hip_fp8_e4m3_fnuz* src1, float* as, float* bs, input_t* dst, int m, int n, int k, int col, int next) {
    next = blockIdx.z >= next ? next : 0;
    int cx = (blockIdx.z - next) << 6;
    input_t& cache = dst[blockIdx.z * col + blockIdx.y];
    if (0 == (threadIdx.x & 31)) {
        int id = threadIdx.x >> 5;
        int stride = next ? (n + 127) >> 7 : m;
        as = next ? bs + (cx >> 7) : as + (cx | blockIdx.x << 3 | id << 1);
        cache.weight_data[blockIdx.x][id] = *(uint64_t*)(as + stride * blockIdx.y);
    }
    m = next ? n : m;
    src = next ? src1 : src;
    uint64_t value = 0;
    cx |= (threadIdx.x >> 6 << 5) | (threadIdx.x & 31);
    int cy = ((blockIdx.y << 3 | blockIdx.x) << 1 | (threadIdx.x >> 5 & 1)) << 3;
    if (cx < m && cy < k) {
        src += cy * m + cx;
        __hip_fp8_e4m3_fnuz buffer[8] = { src[0], src[m], src[2 * m], src[3 * m],
        src[4 * m], src[5 * m], src[6 * m], src[7 * m]};
        value = *reinterpret_cast<uint64_t*>(buffer);
    }
    cache.regs[blockIdx.x][threadIdx.x] = value;
}


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 next = (m + 127) / 128 * 2;
    int row = (n + 127) / 128 * 2 + next;
    int col = (k + 127) / 128;
    auto options = torch::TensorOptions().dtype(torch::kUInt8).device(torch::kCUDA);
    torch::Tensor cache = torch::empty(row * col * sizeof(input_t), options);
    reorder_kernel<<<dim3(8, col, row), dim3(128), 0, 0>>>((__hip_fp8_e4m3_fnuz*)a.data_ptr(), (__hip_fp8_e4m3_fnuz*)b.data_ptr(),
        as.data_ptr<float>(), bs.data_ptr<float>(), (input_t*)cache.data_ptr(), m, n, k, col, next);
    custom_kernel<<<dim3((m+63)/64, (n+63)/64), dim3(256, 1, 1), 0, 0>>> ((input_t*)cache.data_ptr(),
        (__hip_bfloat16*)c.data_ptr(), m, n, k, col, next * col);
}
"""

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


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


python eval.py benchmark /tmp/tmpg5iysgzd
[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: 2
ninja: no work to do.
