# 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 size_t BLOCK = 128;

__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 uint64_t* cache, const float* as, const float* bs, 
                   __hip_bfloat16* c, size_t m, size_t n, size_t k, size_t col, size_t offset) {
    const uint64_t* a = cache;
    const uint64_t* b = cache + offset;
    size_t bx = blockIdx.x * 2 + (threadIdx.y & 1);
    size_t by = blockIdx.y * 2 + (threadIdx.y >> 1);
    size_t cx = 32 * bx;
    size_t cy = 32 * by;
    if(cx >= m || cy >= n) return;
    size_t tx = threadIdx.x & 31;
    size_t ty = threadIdx.x >> 5 & 1;
    size_t sn = (n + BLOCK - 1) >> 7;
    bs += cy >> 7;
    as += cx + tx;
    a += bx * col + threadIdx.x;
    b += by * col + threadIdx.x;
    f32x16 result = { };
    for(size_t i = 0; i < k; i += BLOCK) {
        const auto* ap = a + i * 4;
        const auto* bp = b + i * 4;
        f32x16 block_result = { };
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0], ap[0], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0x40], ap[0x40], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0x80], ap[0x80], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0xc0], ap[0xc0], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0x100], ap[0x100], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0x140], ap[0x140], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0x180], ap[0x180], block_result, 0, 0, 0);
        block_result = __builtin_amdgcn_mfma_f32_32x32x16_fp8_fp8(bp[0x1c0], ap[0x1c0], block_result, 0, 0, 0);
        result += block_result * bs[(i >> 7) * sn] * as[(i >> 7) * m];
    }
    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 permute_kernel(const __hip_fp8_e4m3_fnuz* src, const __hip_fp8_e4m3_fnuz* src1, uint64_t* dst,
    size_t m, size_t n, size_t k, size_t col, size_t as0, size_t as1, size_t bs0, size_t bs1, size_t next) {
    next = blockIdx.x >= next ? next : 0;
    m = next ? n : m;
    as0 = next ? bs0 : as0;
    as1 = next ? bs1 : as1;
    src = next ? src1 : src;
    size_t cx = (blockIdx.x - next) * 32 + (threadIdx.x & 31);
    size_t cy = (blockIdx.y * 2 + (threadIdx.x >> 5 & 1)) * 8;
    uint64_t value = 0;
    if (cx < m && cy < k) {
        src += cy * as1 + cx * as0;
        __hip_fp8_e4m3_fnuz buffer[8] = { src[0], src[as1], src[2 * as1], src[3 * as1],
            src[4 * as1], src[5 * as1], src[6 * as1], src[7 * as1]};
        value = *reinterpret_cast<uint64_t*>(buffer);
    }
    dst[blockIdx.x * col + blockIdx.y * 64 + threadIdx.x] = value;
}

void fp8_mm(torch::Tensor a, torch::Tensor b, torch::Tensor as, torch::Tensor bs, torch::Tensor c) {
    size_t m = a.size(0);
    size_t n = b.size(0);
    size_t k = a.size(1);
    size_t next = (m + 127) / 128 * 4;
    size_t row = (n + 127) / 128 * 4 + next;
    size_t col = (k + 127) / 128 * 512;
    auto options = torch::TensorOptions().dtype(torch::kUInt64).device(torch::kCUDA);
    torch::Tensor cache = torch::empty(row * col, options);
    permute_kernel<<<dim3(row, col / 64), dim3(64), 0, 0>>>((__hip_fp8_e4m3_fnuz*)a.data_ptr(),  (__hip_fp8_e4m3_fnuz*)b.data_ptr(),
        cache.data_ptr<uint64_t>(), m, n, k, col, a.stride(0), a.stride(1), b.stride(0), b.stride(1), next);
    custom_kernel<<<dim3((m+63)/64, (n+63)/64), dim3(64, 4), 0, 0>>> (cache.data_ptr<uint64_t>(),
        as.data_ptr<float>(), bs.data_ptr<float>(), (__hip_bfloat16*)c.data_ptr(), m, n, k, col, next * col);
}
"""

import os
os.environ["CXX"] = "clang++"
os.environ['PYTORCH_ROCM_ARCH'] = 'gfx942'

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