Skip to content
KernelIndex
Search⌘K

submission 725020

yuzhou_lithos · python · License unknown

Use it

Vendorable · source mirrored · license unknownView source →

No package. Vendor the mirrored source: 1032 lines, June 9 Researcher Reciprocity License v1.0.

submission_current.py
curl "https://kernelindex.com/api/v1/implementations/kernelbot-amd-mxfp4-mm-725020?include=source"
interfacepython
Compatibility
measured onAMD Instinct MI355X
declared hardwareAMD Instinct MI355X
architecturesgfx950
dtypesbf16, mxfp4

Benchmark evidence

1 measurement across 1 GPU, fastest first.

Operation / workload
Hardware
Latency
Rank
Observed
AMD MXFP4 GEMMsuite of 6 cases
AMD Instinct MI355X
9.28µs
#152 of 1143
2026-04-04

Reported · How evidence levels are derived →

Source and license

sourceavailable
revision digestsha256:2b0bfdd22563318672936c02953a47b54cf3c8cbe5b99e66c841c15aad0fadde
license declaredunknown
license concludedunknown
authorsyuzhou_lithos
imported2026-08-15

Techniques

Extracted from the mirrored source by pattern, never inferred. Each row cites its line.

fp4MXFP4 GEMM v284_flush_denorm: v268 + allow_flush_denorm=True on all Triton paths.
num-warps = 4num_warps=4, num_stages=1, waves_per_eu=2, matrix_instr_nonkdim=16, NUM_KSPLIT=16),
shared-memory__shared__ float reduce16[4][64 * 4];
split-kand (args["SPLITK_BLOCK_SIZE"] % args["BLOCK_SIZE_K"] == 0)
stages = 1num_warps=4, num_stages=1, waves_per_eu=2, matrix_instr_nonkdim=16, NUM_KSPLIT=16),
tile-k = 256(16, 2112, 7168): dict(BLOCK_SIZE_M=16, BLOCK_SIZE_N=128, BLOCK_SIZE_K=256, GROUP_SIZE_M=1,
tile-m = 16(16, 2112, 7168): dict(BLOCK_SIZE_M=16, BLOCK_SIZE_N=128, BLOCK_SIZE_K=256, GROUP_SIZE_M=1,
tile-n = 128(16, 2112, 7168): dict(BLOCK_SIZE_M=16, BLOCK_SIZE_N=128, BLOCK_SIZE_K=256, GROUP_SIZE_M=1,
vector-width = uint4uint4 a0, a1, a2, a3;

Kernel source

submission_current.py1032 lines
"""
MXFP4 GEMM v284_flush_denorm: v268 + allow_flush_denorm=True on all Triton paths.

HSA_ENABLE_SDMA=0: Disable System DMA, reduces launch overhead for small kernels.
GPU_MAX_HW_QUEUES=8: Use all 8 hardware queues (one per XCD) for better dispatch.
"""
import os
os.environ["PYTORCH_ROCM_ARCH"] = "gfx950"
os.environ["HSA_ENABLE_SDMA"] = "0"  # Disable SDMA — reduces launch overhead for small kernels
os.environ["GPU_MAX_HW_QUEUES"] = "8"  # Use all hardware queues for better XCD utilization
os.environ["TRITON_HIP_USE_BLOCK_PINGPONG"] = "0"

import torch
import triton
import triton.language as tl
from task import input_t, output_t

_HIP_SRC = r"""
#include <hip/hip_runtime.h>
#include <hip/hip_ext_ocp.h>
#include <torch/extension.h>
#include <cstdint>


typedef int __attribute__((ext_vector_type(8))) i32x8;
typedef int __attribute__((ext_vector_type(4))) v4i;
typedef float __attribute__((ext_vector_type(16))) f32x16;
typedef float __attribute__((ext_vector_type(4))) f32x4;
typedef __bf16 bf16v2_t __attribute__((ext_vector_type(2)));

// Buffer resource load: hardware OOB returns 0, no branch needed
__device__ v4i __llvm_amdgcn_raw_buffer_load_v4i32(v4i rsrc, int voff, int soff, int aux)
    __asm("llvm.amdgcn.raw.buffer.load.v4i32");

__device__ __forceinline__ v4i make_buffer_resource(const void* ptr, unsigned range_bytes) {
    v4i r;
    auto p = reinterpret_cast<uintptr_t>(ptr);
    r[0] = (int)(p & 0xFFFFFFFFu);
    r[1] = (int)(p >> 32);
    r[2] = (int)range_bytes;
    r[3] = (int)(4 << 15); // NUM_FORMAT=U32
    return r;
}

// XCD-aware block remapping for MI355X (8 XCDs)
// Distributes consecutive blocks across different XCDs for better load balance
__device__ __forceinline__ int remap_xcd(int pid, int grid_total, int NUM_XCDS = 8) {
    int pids_per_xcd = (grid_total + NUM_XCDS - 1) / NUM_XCDS;
    int tall_xcds = grid_total % NUM_XCDS;
    if (tall_xcds == 0) tall_xcds = NUM_XCDS;
    int xcd = pid % NUM_XCDS;
    int local_pid = pid / NUM_XCDS;
    if (xcd < tall_xcds)
        return xcd * pids_per_xcd + local_pid;
    else
        return tall_xcds * pids_per_xcd + (xcd - tall_xcds) * (pids_per_xcd - 1) + local_pid;
}


__device__ __forceinline__ int pack8_hw(const uint16_t* src, float hs) {
    unsigned int d = 0;
    d = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(d, *reinterpret_cast<const bf16v2_t*>(&src[0]), hs, 0);
    d = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(d, *reinterpret_cast<const bf16v2_t*>(&src[2]), hs, 1);
    d = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(d, *reinterpret_cast<const bf16v2_t*>(&src[4]), hs, 2);
    d = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(d, *reinterpret_cast<const bf16v2_t*>(&src[6]), hs, 3);
    return (int)d;
}

__device__ __forceinline__ void quant_32(const uint16_t* ap, int out[4], int32_t& spk) {
    uint16_t mx = 0;
    #pragma unroll
    for (int j = 0; j < 32; j++) mx = max(mx, (uint16_t)(ap[j] & 0x7FFF));
    uint32_t au = (((uint32_t)mx << 16) + 0x200000u) & 0xFF800000u;
    int ef = (au >> 23u) & 0xFFu;
    int su = (au == 0u) ? -127 : max(-127, min(127, ef - 127 - 2));
    float hs = (su >= -126) ? __uint_as_float((uint32_t)(su + 127) << 23) : 0.0f;
    #pragma unroll
    for (int j = 0; j < 4; j++) out[j] = pack8_hw(&ap[j * 8], hs);
    spk = (int32_t)(uint8_t)(su + 127);
}

__device__ __forceinline__ int32_t load_b_scale(const uint8_t* Bsc,
    int ng, int bb, int SNG, int N) {
    if (ng >= N) return 127;
    int ifl = (ng/32)*(SNG*256) + (bb/8)*256 + (bb%4)*64
            + (ng%16)*4 + ((bb%8)/4)*2 + (ng%32)/16;
    return (int32_t)Bsc[ifl];
}

// ============================================================================
// 16x16x128 MFMA KERNEL with B_SHUFFLE (micro-optimized) + XCD remap
// ============================================================================
__global__ void __launch_bounds__(256, 2)
gemm_fused_16x16_bsh_kernel(
    const uint16_t* __restrict__ A, const uint8_t* __restrict__ Bsh,
    const uint8_t* __restrict__ Bsc, uint16_t* __restrict__ C,
    int M, int N, int K, int strA, int BscSN)
{
    int pid = blockIdx.x * gridDim.y + blockIdx.y;
    pid = remap_xcd(pid, gridDim.x * gridDim.y);
    const int mt = pid / (int)gridDim.y, nt = pid % (int)gridDim.y;
    const int wid = threadIdx.x >> 6;
    const int lid = threadIdx.x & 63;
    const int t_row = lid & 15;
    const int kpart = lid >> 4;
    const int SNG = BscSN >> 3;
    const int m_row = (mt << 4) + t_row;
    const int b_ng = (nt << 4) + t_row;

    int total_steps = K >> 7;
    int steps_per_warp = (total_steps + 3) >> 2;
    int k_start = wid * steps_per_warp * 128;
    int k_end = min(k_start + steps_per_warp * 128, K);

    const bool a_valid = (m_row < M);
    const int a_base = m_row * strA + (kpart << 5);
    const bool b_valid = (b_ng < N);
    const int nkt = K >> 5;
    const int bsh_kb_base = b_valid ? ((b_ng >> 4) * nkt * 256 + (b_ng & 15) * 16 + (kpart << 8)) : 0;
    const int bk_limit = (K >> 1) - 15;
    const int bsc_ng_base = b_valid ?
        ((b_ng >> 5) * (SNG << 8) + ((b_ng & 15) << 2) + ((b_ng & 31) >> 4)) : 0;
    int bb = (k_start >> 5) + kpart;

    f32x4 c_acc = {0.0f, 0.0f, 0.0f, 0.0f};

    for (int kb = k_start; kb < k_end; kb += 128) {
        int k_off = kb + (kpart << 5);
        int bk = (kb >> 1) + (kpart << 4);

        uint4 a0, a1, a2, a3;
        if (a_valid && k_off + 31 < K) {
            const uint4* src = reinterpret_cast<const uint4*>(&A[a_base + kb]);
            a0 = src[0]; a1 = src[1]; a2 = src[2]; a3 = src[3];
        } else {
            a0 = {0,0,0,0}; a1 = {0,0,0,0}; a2 = {0,0,0,0}; a3 = {0,0,0,0};
        }

        int b_i32[4];
        if (b_valid && bk < bk_limit) {
            uint4 bd = *reinterpret_cast<const uint4*>(&Bsh[bsh_kb_base + ((kb >> 5) << 8)]);
            b_i32[0]=((int*)&bd)[0]; b_i32[1]=((int*)&bd)[1];
            b_i32[2]=((int*)&bd)[2]; b_i32[3]=((int*)&bd)[3];
        } else { b_i32[0]=0; b_i32[1]=0; b_i32[2]=0; b_i32[3]=0; }

        int32_t b_spk = b_valid ?
            (int32_t)Bsc[bsc_ng_base + ((bb >> 3) << 8) + ((bb & 3) << 6) + (((bb & 7) >> 2) << 1)]
            : (int32_t)127;
        bb += 4;

        uint16_t a_local[32];
        uint4* dst = reinterpret_cast<uint4*>(a_local);
        dst[0] = a0; dst[1] = a1; dst[2] = a2; dst[3] = a3;
        int a_i32[4]; int32_t a_spk;
        quant_32(a_local, a_i32, a_spk);

        i32x8 am = {a_i32[0], a_i32[1], a_i32[2], a_i32[3], 0, 0, 0, 0};
        i32x8 bm = {b_i32[0], b_i32[1], b_i32[2], b_i32[3], 0, 0, 0, 0};
        c_acc = __builtin_amdgcn_mfma_scale_f32_16x16x128_f8f6f4(
            am, bm, c_acc, 4, 4, 0, a_spk, 0, b_spk);
    }

    __shared__ float reduce16[4][64 * 4];
    #pragma unroll
    for (int i = 0; i < 4; i++)
        reduce16[wid][lid + (i << 6)] = c_acc[i];
    __syncthreads();

    if (wid == 0) {
        #pragma unroll
        for (int j = 0; j < 4; j++) {
            int off = lid + (j << 6);
            float sum = reduce16[0][off] + reduce16[1][off]
                      + reduce16[2][off] + reduce16[3][off];
            int mo = (mt << 4) + (kpart << 2) + j;
            int no = (nt << 4) + t_row;
            if (mo < M && no < N) {
                uint32_t fp = __float_as_uint(sum);
                fp += 0x7FFFu + ((fp >> 16) & 1u);
                C[mo * N + no] = (uint16_t)(fp >> 16u);
            }
        }
    }
}

// ============================================================================
// ROW-MAJOR A QUANT KERNEL (bf16 -> fp4x2 + e8m0 ROW-MAJOR scales)
// Used for Triton GEMM path (expects simple [M, K/32] scale layout)
// ============================================================================
__global__ void __launch_bounds__(64, 16)
quant_a_rowmajor_kernel(const uint16_t* __restrict__ A, uint8_t* __restrict__ Aq,
                        uint8_t* __restrict__ Asc, int M, int K, int strA) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int n_scales = K / 32;
    int total_blocks = M * n_scales;
    if (idx >= total_blocks) return;

    int row = idx / n_scales;
    int blk = idx % n_scales;
    int k_off = blk * 32;

    uint16_t vals[32];
    if (row < M) {
        const uint4* src = reinterpret_cast<const uint4*>(&A[row * strA + k_off]);
        uint4* dst = reinterpret_cast<uint4*>(vals);
        dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3];
    } else {
        #pragma unroll
        for (int j = 0; j < 32; j++) vals[j] = 0;
    }

    uint16_t mx = 0;
    #pragma unroll
    for (int j = 0; j < 32; j++) mx = max(mx, (uint16_t)(vals[j] & 0x7FFF));

    uint32_t au = (((uint32_t)mx << 16) + 0x200000u) & 0xFF800000u;
    int ef = (au >> 23u) & 0xFFu;
    int su = (au == 0u) ? -127 : max(-127, min(127, ef - 127 - 2));
    float hs = (su >= -126) ? __uint_as_float((uint32_t)(su + 127) << 23) : 0.0f;
    uint8_t scale_val = (uint8_t)(su + 127);

    unsigned int packed[4];
    packed[0] = 0;
    packed[0] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[0], *reinterpret_cast<bf16v2_t*>(&vals[0]), hs, 0);
    packed[0] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[0], *reinterpret_cast<bf16v2_t*>(&vals[2]), hs, 1);
    packed[0] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[0], *reinterpret_cast<bf16v2_t*>(&vals[4]), hs, 2);
    packed[0] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[0], *reinterpret_cast<bf16v2_t*>(&vals[6]), hs, 3);
    packed[1] = 0;
    packed[1] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[1], *reinterpret_cast<bf16v2_t*>(&vals[8]), hs, 0);
    packed[1] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[1], *reinterpret_cast<bf16v2_t*>(&vals[10]), hs, 1);
    packed[1] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[1], *reinterpret_cast<bf16v2_t*>(&vals[12]), hs, 2);
    packed[1] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[1], *reinterpret_cast<bf16v2_t*>(&vals[14]), hs, 3);
    packed[2] = 0;
    packed[2] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[2], *reinterpret_cast<bf16v2_t*>(&vals[16]), hs, 0);
    packed[2] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[2], *reinterpret_cast<bf16v2_t*>(&vals[18]), hs, 1);
    packed[2] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[2], *reinterpret_cast<bf16v2_t*>(&vals[20]), hs, 2);
    packed[2] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[2], *reinterpret_cast<bf16v2_t*>(&vals[22]), hs, 3);
    packed[3] = 0;
    packed[3] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[3], *reinterpret_cast<bf16v2_t*>(&vals[24]), hs, 0);
    packed[3] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[3], *reinterpret_cast<bf16v2_t*>(&vals[26]), hs, 1);
    packed[3] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[3], *reinterpret_cast<bf16v2_t*>(&vals[28]), hs, 2);
    packed[3] = __builtin_amdgcn_cvt_scalef32_pk_fp4_bf16(packed[3], *reinterpret_cast<bf16v2_t*>(&vals[30]), hs, 3);

    if (row < M) {
        int out_off = row * (K / 2) + blk * 16;
        *reinterpret_cast<uint4*>(&Aq[out_off]) = *reinterpret_cast<uint4*>(packed);
    }

    // Row-major scale layout: [M, K/32]
    Asc[row * n_scales + blk] = scale_val;
}

// ============================================================================
// Pybind11 module
// ============================================================================
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    // HIP dispatch for M<=32 K<=1024 (fused 16x16x128 MFMA)
    m.def("dispatch_gemm", [](torch::Tensor A,
            torch::Tensor Bq, torch::Tensor Bsh, torch::Tensor Bsc,
            int64_t N,
            torch::Tensor fp32_ws, torch::Tensor bf16_out,
            torch::Tensor aq_buf, torch::Tensor asc_buf, torch::Tensor asm_out) -> torch::Tensor {
        int M = (int)A.size(0), K = (int)A.size(1);
        const uint16_t* Ap = reinterpret_cast<const uint16_t*>(A.data_ptr());
        const uint8_t* Bshp = reinterpret_cast<const uint8_t*>(Bsh.data_ptr());
        const uint8_t* Bscp = reinterpret_cast<const uint8_t*>(Bsc.data_ptr());
        int strA = (int)A.stride(0);
        int BscSN = (int)Bsc.size(1);

        dim3 grid((M + 15) / 16, ((int)N + 15) / 16);
        gemm_fused_16x16_bsh_kernel<<<grid, 256>>>(
            Ap, Bshp, Bscp,
            reinterpret_cast<uint16_t*>(bf16_out.data_ptr()),
            M, (int)N, K, strA, BscSN);
        return bf16_out;
    });
    // Row-major quant for Triton path
    m.def("quant_a_rowmajor", [](torch::Tensor A, torch::Tensor aq, torch::Tensor asc,
                                  int64_t M, int64_t K) {
        int n_scales = (int)K / 32;
        int total_blocks = (int)M * n_scales;
        quant_a_rowmajor_kernel<<<(total_blocks + 63) / 64, 64>>>(
            reinterpret_cast<const uint16_t*>(A.data_ptr()),
            reinterpret_cast<uint8_t*>(aq.data_ptr()),
            reinterpret_cast<uint8_t*>(asc.data_ptr()),
            (int)M, (int)K, (int)A.stride(0));
    });
}
"""

_EXT = None
def _get_ext():
    global _EXT
    if _EXT is None:
        import torch.utils.cpp_extension as _cext
        _EXT = _cext.load_inline(
            name="fused_mxfp4_v232",
            cpp_sources=[""],
            cuda_sources=[_HIP_SRC],
            extra_cuda_cflags=["-O3", "-std=c++17", "--offload-arch=gfx950"],
            verbose=False,
        )
    return _EXT


# ============================================================================
# Triton kernels for M>=64 (from competitor, proven faster than ASM GEMM)
# ============================================================================

@triton.jit
def _triton_remap_xcd(pid, GRID_MN, NUM_XCDS: tl.constexpr = 8):
    pids_per_xcd = (GRID_MN + NUM_XCDS - 1) // NUM_XCDS
    tall_xcds = GRID_MN % NUM_XCDS
    tall_xcds = NUM_XCDS if tall_xcds == 0 else tall_xcds
    xcd = pid % NUM_XCDS
    local_pid = pid // NUM_XCDS
    if xcd < tall_xcds:
        pid = xcd * pids_per_xcd + local_pid
    else:
        pid = (
            tall_xcds * pids_per_xcd
            + (xcd - tall_xcds) * (pids_per_xcd - 1)
            + local_pid
        )
    return pid


@triton.jit
def _triton_pid_grid(pid: int, num_pid_m: int, num_pid_n: int, GROUP_SIZE_M: tl.constexpr = 1):
    if GROUP_SIZE_M == 1:
        pid_m = pid // num_pid_n
        pid_n = pid % num_pid_n
    else:
        num_pid_in_group = GROUP_SIZE_M * num_pid_n
        group_id = pid // num_pid_in_group
        first_pid_m = group_id * GROUP_SIZE_M
        group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
        tl.assume(group_size_m >= 0)
        pid_m = first_pid_m + (pid % group_size_m)
        pid_n = (pid % num_pid_in_group) // group_size_m
    return pid_m, pid_n


@triton.jit
def _triton_shuffled_b_scale_offset(row, col, Ks_stride):
    return (
        (row // 32) * (Ks_stride * 32)
        + (col // 8) * 256
        + (col % 4) * 64
        + (row % 16) * 4
        + ((col // 4) % 2) * 2
        + ((row // 16) % 2)
    )


# ============================================================================
# Triton inline MXFP4 quantization (for fused kernel path)
# ============================================================================

@triton.jit
def _mxfp4_quant_inline(
    x,
    BLOCK_SIZE_K: tl.constexpr,
    BLOCK_SIZE_M: tl.constexpr,
    MXFP4_QUANT_BLOCK_SIZE: tl.constexpr,
):
    EXP_BIAS_FP32: tl.constexpr = 127
    EXP_BIAS_FP4: tl.constexpr = 1
    MBITS_F32: tl.constexpr = 23
    MBITS_FP4: tl.constexpr = 1
    EBITS_F32: tl.constexpr = 8
    EBITS_FP4: tl.constexpr = 2

    max_normal: tl.constexpr = 6
    min_normal: tl.constexpr = 1

    NUM_QUANT_BLOCKS: tl.constexpr = BLOCK_SIZE_K // MXFP4_QUANT_BLOCK_SIZE
    x = x.reshape(BLOCK_SIZE_M, NUM_QUANT_BLOCKS, MXFP4_QUANT_BLOCK_SIZE)

    amax = tl.max(tl.abs(x), axis=-1, keep_dims=True)
    amax = amax.to(tl.int32, bitcast=True)
    amax = (amax + 0x200000).to(tl.uint32, bitcast=True) & 0xFF800000
    amax = amax.to(tl.float32, bitcast=True)
    scale_e8m0_unbiased = tl.log2(amax).floor() - 2
    scale_e8m0_unbiased = tl.clamp(scale_e8m0_unbiased, min=-127, max=127)

    bs_e8m0 = scale_e8m0_unbiased.to(tl.uint8) + 127
    quant_scale = tl.exp2(-scale_e8m0_unbiased)

    qx = x * quant_scale
    qx = qx.to(tl.uint32, bitcast=True)

    s = qx & 0x80000000
    qx = qx ^ s

    qx_fp32 = qx.to(tl.float32, bitcast=True)
    saturate_mask = qx_fp32 >= max_normal
    denormal_mask = (not saturate_mask) & (qx_fp32 < min_normal)
    normal_mask = not (saturate_mask | denormal_mask)

    denorm_exp: tl.constexpr = (EXP_BIAS_FP32 - EXP_BIAS_FP4) + (MBITS_F32 - MBITS_FP4) + 1
    denorm_mask_int: tl.constexpr = denorm_exp << MBITS_F32
    denorm_mask_float: tl.constexpr = tl.cast(denorm_mask_int, tl.float32, bitcast=True)

    denormal_x = qx_fp32 + denorm_mask_float
    denormal_x = denormal_x.to(tl.uint32, bitcast=True)
    denormal_x -= denorm_mask_int
    denormal_x = denormal_x.to(tl.uint8)

    normal_x = qx
    mant_odd = (normal_x >> (MBITS_F32 - MBITS_FP4)) & 1
    val_to_add = ((EXP_BIAS_FP4 - EXP_BIAS_FP32) << MBITS_F32) + (1 << 21) - 1
    normal_x += val_to_add
    normal_x += mant_odd
    normal_x = normal_x >> (MBITS_F32 - MBITS_FP4)
    normal_x = normal_x.to(tl.uint8)

    e2m1_value = tl.full(qx.type.get_block_shapes(), 0x7, dtype=tl.uint8)
    e2m1_value = tl.where(normal_mask, normal_x, e2m1_value)
    e2m1_value = tl.where(denormal_mask, denormal_x, e2m1_value)

    sign_lp = s >> (MBITS_F32 + EBITS_F32 - MBITS_FP4 - EBITS_FP4)
    sign_lp = sign_lp.to(tl.uint8)
    e2m1_value = e2m1_value | sign_lp

    e2m1_value = tl.reshape(
        e2m1_value, [BLOCK_SIZE_M, NUM_QUANT_BLOCKS, MXFP4_QUANT_BLOCK_SIZE // 2, 2]
    )
    evens, odds = tl.split(e2m1_value)
    x_fp4 = evens | (odds << 4)
    x_fp4 = x_fp4.reshape(BLOCK_SIZE_M, BLOCK_SIZE_K // 2)

    return x_fp4, bs_e8m0.reshape(BLOCK_SIZE_M, NUM_QUANT_BLOCKS)


# ============================================================================
# Triton FUSED GEMM kernel (inline BF16->FP4 quant, for M=16 K>1024)
# ============================================================================

@triton.heuristics(
    {
        "EVEN_K": lambda args: (args["K"] % (args["BLOCK_SIZE_K"] // 2) == 0)
        and (args["SPLITK_BLOCK_SIZE"] % args["BLOCK_SIZE_K"] == 0)
        and (args["K"] % (args["SPLITK_BLOCK_SIZE"] // 2) == 0),
    }
)
@triton.jit
def _fused_gemm_fp4_kernel(
    a_bf16_ptr, b_ptr, c_ptr,
    b_scales_ptr,
    M, N, K,
    actual_K,
    Ks_stride,
    stride_am, stride_ak,
    stride_bk, stride_bn,
    stride_ck, stride_cm, stride_cn,
    BLOCK_SIZE_M: tl.constexpr,
    BLOCK_SIZE_N: tl.constexpr,
    BLOCK_SIZE_K: tl.constexpr,
    GROUP_SIZE_M: tl.constexpr,
    NUM_KSPLIT: tl.constexpr,
    SPLITK_BLOCK_SIZE: tl.constexpr,
    EVEN_K: tl.constexpr,
    num_warps: tl.constexpr,
    num_stages: tl.constexpr,
    waves_per_eu: tl.constexpr,
    matrix_instr_nonkdim: tl.constexpr,
):
    tl.assume(stride_am > 0)
    tl.assume(stride_ak > 0)
    tl.assume(stride_bk > 0)
    tl.assume(stride_bn > 0)
    tl.assume(stride_cm > 0)
    tl.assume(stride_cn > 0)

    GRID_MN = tl.cdiv(M, BLOCK_SIZE_M) * tl.cdiv(N, BLOCK_SIZE_N)
    pid_unified = tl.program_id(axis=0)
    pid_unified = _triton_remap_xcd(pid_unified, GRID_MN * NUM_KSPLIT, NUM_XCDS=8)

    pid_k = pid_unified % NUM_KSPLIT
    pid = pid_unified // NUM_KSPLIT
    num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
    num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)

    if NUM_KSPLIT == 1:
        pid_m, pid_n = _triton_pid_grid(pid, num_pid_m, num_pid_n, GROUP_SIZE_M=GROUP_SIZE_M)
    else:
        pid_m = pid // num_pid_n
        pid_n = pid % num_pid_n

    tl.assume(pid_m >= 0)
    tl.assume(pid_n >= 0)

    SCALE_GROUP_SIZE: tl.constexpr = 32
    SCALES_PER_KBLOCK: tl.constexpr = BLOCK_SIZE_K // SCALE_GROUP_SIZE

    if (pid_k * SPLITK_BLOCK_SIZE // 2) < K:
        num_k_iter = tl.cdiv(SPLITK_BLOCK_SIZE // 2, BLOCK_SIZE_K // 2)

        offs_k_packed = tl.arange(0, BLOCK_SIZE_K // 2)
        offs_k_packed_split = pid_k * (SPLITK_BLOCK_SIZE // 2) + offs_k_packed

        offs_k_actual = tl.arange(0, BLOCK_SIZE_K)
        offs_k_actual_split = pid_k * SPLITK_BLOCK_SIZE + offs_k_actual

        offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
        offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N

        a_bf16_ptrs = a_bf16_ptr + (offs_am[:, None] * stride_am + offs_k_actual_split[None, :] * stride_ak)
        b_ptrs = b_ptr + (offs_k_packed_split[:, None] * stride_bk + offs_bn[None, :] * stride_bn)

        ks_base = pid_k * (SPLITK_BLOCK_SIZE // SCALE_GROUP_SIZE)
        offs_ks_local = tl.arange(0, SCALES_PER_KBLOCK)

        accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)

        for k_iter in range(pid_k * num_k_iter, (pid_k + 1) * num_k_iter):
            if EVEN_K:
                a_bf16 = tl.load(a_bf16_ptrs)
            else:
                a_bf16 = tl.load(a_bf16_ptrs, mask=offs_k_actual[None, :] < actual_K - k_iter * BLOCK_SIZE_K, other=0.0)

            a_f32 = a_bf16.to(tl.float32)
            a_fp4, a_scales = _mxfp4_quant_inline(a_f32, BLOCK_SIZE_K, BLOCK_SIZE_M, SCALE_GROUP_SIZE)

            cur_offs_ks = ks_base + offs_ks_local
            b_scale_offsets = _triton_shuffled_b_scale_offset(offs_bn[:, None], cur_offs_ks[None, :], Ks_stride)
            b_scales = tl.load(b_scales_ptr + b_scale_offsets, cache_modifier=".cg")

            if EVEN_K:
                b = tl.load(b_ptrs, cache_modifier=".cg")
            else:
                b = tl.load(b_ptrs, mask=offs_k_packed[:, None] < K - k_iter * (BLOCK_SIZE_K // 2), other=0, cache_modifier=".cg")

            accumulator = tl.dot_scaled(a_fp4, a_scales, "e2m1", b, b_scales, "e2m1", accumulator)

            a_bf16_ptrs += BLOCK_SIZE_K * stride_ak
            b_ptrs += (BLOCK_SIZE_K // 2) * stride_bk
            ks_base += SCALES_PER_KBLOCK

        c = accumulator.to(c_ptr.type.element_ty)

        offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64)
        offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)
        c_ptrs = (
            c_ptr
            + stride_cm * offs_cm[:, None]
            + stride_cn * offs_cn[None, :]
            + pid_k * stride_ck
        )
        c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N)
        tl.store(c_ptrs, c, mask=c_mask)


# ============================================================================
# Triton GEMM kernel with pre-quantized A (for M>=64)
# ============================================================================

@triton.heuristics(
    {
        "EVEN_K": lambda args: (args["K"] % (args["BLOCK_SIZE_K"] // 2) == 0)
        and (args["SPLITK_BLOCK_SIZE"] % args["BLOCK_SIZE_K"] == 0)
        and (args["K"] % (args["SPLITK_BLOCK_SIZE"] // 2) == 0),
    }
)
@triton.jit
def _gemm_fp4_kernel(
    a_ptr, b_ptr, c_ptr,
    a_scales_ptr, b_scales_ptr,
    M, N, K,
    Ks_stride,
    stride_am, stride_ak,
    stride_bk, stride_bn,
    stride_ck, stride_cm, stride_cn,
    stride_asm, stride_ask,
    BLOCK_SIZE_M: tl.constexpr,
    BLOCK_SIZE_N: tl.constexpr,
    BLOCK_SIZE_K: tl.constexpr,
    GROUP_SIZE_M: tl.constexpr,
    NUM_KSPLIT: tl.constexpr,
    SPLITK_BLOCK_SIZE: tl.constexpr,
    EVEN_K: tl.constexpr,
    num_warps: tl.constexpr,
    num_stages: tl.constexpr,
    waves_per_eu: tl.constexpr,
    matrix_instr_nonkdim: tl.constexpr,
):
    tl.assume(stride_am > 0)
    tl.assume(stride_ak > 0)
    tl.assume(stride_bk > 0)
    tl.assume(stride_bn > 0)
    tl.assume(stride_cm > 0)
    tl.assume(stride_cn > 0)
    tl.assume(stride_asm > 0)
    tl.assume(stride_ask > 0)

    GRID_MN = tl.cdiv(M, BLOCK_SIZE_M) * tl.cdiv(N, BLOCK_SIZE_N)
    pid_unified = tl.program_id(axis=0)
    pid_unified = _triton_remap_xcd(pid_unified, GRID_MN * NUM_KSPLIT, NUM_XCDS=8)

    pid_k = pid_unified % NUM_KSPLIT
    pid = pid_unified // NUM_KSPLIT
    num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
    num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)

    if NUM_KSPLIT == 1:
        pid_m, pid_n = _triton_pid_grid(pid, num_pid_m, num_pid_n, GROUP_SIZE_M=GROUP_SIZE_M)
    else:
        pid_m = pid // num_pid_n
        pid_n = pid % num_pid_n

    tl.assume(pid_m >= 0)
    tl.assume(pid_n >= 0)

    SCALE_GROUP_SIZE: tl.constexpr = 32
    SCALES_PER_KBLOCK: tl.constexpr = BLOCK_SIZE_K // SCALE_GROUP_SIZE

    if (pid_k * SPLITK_BLOCK_SIZE // 2) < K:
        num_k_iter = tl.cdiv(SPLITK_BLOCK_SIZE // 2, BLOCK_SIZE_K // 2)

        offs_k = tl.arange(0, BLOCK_SIZE_K // 2)
        offs_k_split = pid_k * (SPLITK_BLOCK_SIZE // 2) + offs_k
        offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
        offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N

        a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_k_split[None, :] * stride_ak)
        b_ptrs = b_ptr + (offs_k_split[:, None] * stride_bk + offs_bn[None, :] * stride_bn)

        offs_a_ks = (pid_k * (SPLITK_BLOCK_SIZE // SCALE_GROUP_SIZE)) + tl.arange(0, SCALES_PER_KBLOCK)
        a_scale_ptrs = a_scales_ptr + offs_am[:, None] * stride_asm + offs_a_ks[None, :] * stride_ask

        ks_base = pid_k * (SPLITK_BLOCK_SIZE // SCALE_GROUP_SIZE)
        offs_ks_local = tl.arange(0, SCALES_PER_KBLOCK)

        accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)

        for k in range(pid_k * num_k_iter, (pid_k + 1) * num_k_iter):
            a_scales = tl.load(a_scale_ptrs)

            cur_offs_ks = ks_base + offs_ks_local
            b_scale_offsets = _triton_shuffled_b_scale_offset(offs_bn[:, None], cur_offs_ks[None, :], Ks_stride)
            b_scales = tl.load(b_scales_ptr + b_scale_offsets, cache_modifier=".cg")

            if EVEN_K:
                a = tl.load(a_ptrs)
                b = tl.load(b_ptrs, cache_modifier=".cg")
            else:
                a = tl.load(a_ptrs, mask=offs_k[None, :] < K - k * (BLOCK_SIZE_K // 2), other=0)
                b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k * (BLOCK_SIZE_K // 2), other=0, cache_modifier=".cg")

            accumulator = tl.dot_scaled(a, a_scales, "e2m1", b, b_scales, "e2m1", accumulator)

            a_ptrs += (BLOCK_SIZE_K // 2) * stride_ak
            b_ptrs += (BLOCK_SIZE_K // 2) * stride_bk
            a_scale_ptrs += SCALES_PER_KBLOCK * stride_ask
            ks_base += SCALES_PER_KBLOCK

        c = accumulator.to(c_ptr.type.element_ty)

        offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64)
        offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)
        c_ptrs = (
            c_ptr
            + stride_cm * offs_cm[:, None]
            + stride_cn * offs_cn[None, :]
            + pid_k * stride_ck
        )
        c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N)
        tl.store(c_ptrs, c, mask=c_mask)


@triton.jit
def _reduce_kernel(
    c_in_ptr, c_out_ptr,
    M, N,
    stride_c_in_k, stride_c_in_m, stride_c_in_n,
    stride_c_out_m, stride_c_out_n,
    BLOCK_SIZE_M: tl.constexpr,
    BLOCK_SIZE_N: tl.constexpr,
    ACTUAL_KSPLIT: tl.constexpr,
    MAX_KSPLIT: tl.constexpr,
):
    pid_m = tl.program_id(axis=0)
    pid_n = tl.program_id(axis=1)

    offs_m = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
    offs_n = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
    offs_k = tl.arange(0, MAX_KSPLIT)

    c_in_ptrs = (
        c_in_ptr
        + (offs_k[:, None, None] * stride_c_in_k)
        + (offs_m[None, :, None] * stride_c_in_m)
        + (offs_n[None, None, :] * stride_c_in_n)
    )

    if ACTUAL_KSPLIT == MAX_KSPLIT:
        c = tl.load(c_in_ptrs)
    else:
        c = tl.load(c_in_ptrs, mask=offs_k[:, None, None] < ACTUAL_KSPLIT)
    c = tl.sum(c, axis=0)
    c = c.to(c_out_ptr.type.element_ty)

    c_out_ptrs = (
        c_out_ptr
        + (offs_m[:, None] * stride_c_out_m)
        + (offs_n[None, :] * stride_c_out_n)
    )
    tl.store(c_out_ptrs, c)


# ============================================================================
# Triton configs for M>=16 (fused) and M>=64 (separate quant)
# ============================================================================

# Per-shape tuned configs (from competitor benchmarks)
TRITON_SHAPE_CONFIGS = {
    # M=16 fused path configs
    (16, 2112, 7168): dict(BLOCK_SIZE_M=16, BLOCK_SIZE_N=128, BLOCK_SIZE_K=256, GROUP_SIZE_M=1,
                           num_warps=4, num_stages=1, waves_per_eu=2, matrix_instr_nonkdim=16, NUM_KSPLIT=16),
    # M>=64 separate quant path configs
    (64, 7168, 2048): dict(BLOCK_SIZE_M=32, BLOCK_SIZE_N=64, BLOCK_SIZE_K=512, GROUP_SIZE_M=4,
                           num_warps=4, num_stages=5, waves_per_eu=1, matrix_instr_nonkdim=16, NUM_KSPLIT=1),
    (256, 3072, 1536): dict(BLOCK_SIZE_M=64, BLOCK_SIZE_N=64, BLOCK_SIZE_K=512, GROUP_SIZE_M=4,
                            num_warps=8, num_stages=4, waves_per_eu=2, matrix_instr_nonkdim=16, NUM_KSPLIT=1),
}

# Fallback configs by M threshold
TRITON_FALLBACK_CONFIGS = {
    16: dict(BLOCK_SIZE_M=16, BLOCK_SIZE_N=64, BLOCK_SIZE_K=512, GROUP_SIZE_M=1,
             num_warps=4, num_stages=1, waves_per_eu=2, matrix_instr_nonkdim=16, NUM_KSPLIT=8),
    64: dict(BLOCK_SIZE_M=64, BLOCK_SIZE_N=256, BLOCK_SIZE_K=256, GROUP_SIZE_M=1,
             num_warps=4, num_stages=3, waves_per_eu=2, matrix_instr_nonkdim=32, NUM_KSPLIT=1),
    256: dict(BLOCK_SIZE_M=128, BLOCK_SIZE_N=256, BLOCK_SIZE_K=256, GROUP_SIZE_M=2,
              num_warps=4, num_stages=3, waves_per_eu=2, matrix_instr_nonkdim=32, NUM_KSPLIT=1),
}


def _get_triton_config(M, N, K):
    """Get Triton kernel config for a given shape."""
    key = (M, N, K)
    if key in TRITON_SHAPE_CONFIGS:
        return TRITON_SHAPE_CONFIGS[key].copy()
    for threshold in sorted(TRITON_FALLBACK_CONFIGS.keys()):
        if M <= threshold:
            return TRITON_FALLBACK_CONFIGS[threshold].copy()
    return TRITON_FALLBACK_CONFIGS[256].copy()


def _get_triton_splitk(K_packed, BLOCK_SIZE_K, NUM_KSPLIT):
    """Compute split-K parameters for Triton kernel."""
    NUM_KSPLIT_STEP = 2
    BLOCK_SIZE_K_STEP = 2
    SPLITK_BLOCK_SIZE = (
        triton.cdiv((2 * triton.cdiv(K_packed, NUM_KSPLIT)), BLOCK_SIZE_K) * BLOCK_SIZE_K
    )
    while NUM_KSPLIT > 1 and BLOCK_SIZE_K > 16:
        if (
            K_packed % (SPLITK_BLOCK_SIZE // 2) == 0
            and SPLITK_BLOCK_SIZE % BLOCK_SIZE_K == 0
            and K_packed % (BLOCK_SIZE_K // 2) == 0
        ):
            break
        elif K_packed % (SPLITK_BLOCK_SIZE // 2) != 0 and NUM_KSPLIT > 1:
            NUM_KSPLIT = NUM_KSPLIT // NUM_KSPLIT_STEP
        elif SPLITK_BLOCK_SIZE % BLOCK_SIZE_K != 0:
            if NUM_KSPLIT > 1:
                NUM_KSPLIT = NUM_KSPLIT // NUM_KSPLIT_STEP
            elif BLOCK_SIZE_K > 16:
                BLOCK_SIZE_K = BLOCK_SIZE_K // BLOCK_SIZE_K_STEP
        elif K_packed % (BLOCK_SIZE_K // 2) != 0 and BLOCK_SIZE_K > 16:
            BLOCK_SIZE_K = BLOCK_SIZE_K // BLOCK_SIZE_K_STEP
        else:
            break
        SPLITK_BLOCK_SIZE = (
            triton.cdiv((2 * triton.cdiv(K_packed, NUM_KSPLIT)), BLOCK_SIZE_K) * BLOCK_SIZE_K
        )
    NUM_KSPLIT = triton.cdiv(K_packed, (SPLITK_BLOCK_SIZE // 2))
    return SPLITK_BLOCK_SIZE, BLOCK_SIZE_K, NUM_KSPLIT


# ============================================================================
# Buffer caches
# ============================================================================

_ws_cache = {}
_triton_cache = {}


def custom_kernel(data: input_t) -> output_t:
    A, B, B_q, B_shuffle, B_scale_sh = data
    ext = _get_ext()
    M, K, N = A.shape[0], A.shape[1], B.shape[0]

    if M >= 64:
        # ================================================================
        # Triton GEMM path for M>=64 (separate quant, 8.6% faster than ASM)
        # ================================================================
        K_packed = K // 2
        dev = A.device

        # Get or create workspace buffers for Triton path
        tkey = (M, K, N)
        if tkey not in _triton_cache:
            aq = torch.empty(M, K_packed, dtype=torch.uint8, device=dev)
            asc = torch.empty(M, K // 32, dtype=torch.uint8, device=dev)
            _triton_cache[tkey] = (aq, asc)
        aq_buf, asc_buf = _triton_cache[tkey]

        # Quantize A with row-major scales (for Triton kernel)
        ext.quant_a_rowmajor(A, aq_buf, asc_buf, M, K)

        # Get Triton config
        config = _get_triton_config(M, N, K)

        # Handle split-K
        if config["NUM_KSPLIT"] > 1:
            SPLITK_BLOCK_SIZE, BLOCK_SIZE_K, NUM_KSPLIT = _get_triton_splitk(
                K_packed, config["BLOCK_SIZE_K"], config["NUM_KSPLIT"]
            )
            config["SPLITK_BLOCK_SIZE"] = SPLITK_BLOCK_SIZE
            config["BLOCK_SIZE_K"] = BLOCK_SIZE_K
            config["NUM_KSPLIT"] = NUM_KSPLIT
        else:
            config["SPLITK_BLOCK_SIZE"] = 2 * K_packed

        if config["BLOCK_SIZE_K"] >= 2 * K_packed:
            config["BLOCK_SIZE_K"] = triton.next_power_of_2(2 * K_packed)
            config["SPLITK_BLOCK_SIZE"] = 2 * K_packed
            config["NUM_KSPLIT"] = 1

        config["BLOCK_SIZE_K"] = max(config["BLOCK_SIZE_K"], 128)

        NUM_KSPLIT = config["NUM_KSPLIT"]

        # B data for Triton (transposed layout)
        B_q_u8 = B_q.view(torch.uint8) if B_q.dtype != torch.uint8 else B_q
        B_t = B_q_u8.T
        B_scale_sh_u8 = B_scale_sh.view(torch.uint8) if B_scale_sh.dtype != torch.uint8 else B_scale_sh
        Ks_stride = B_scale_sh_u8.shape[1]

        # Output tensors
        out_key = (M, N, NUM_KSPLIT, dev)
        if out_key not in _ws_cache:
            if NUM_KSPLIT > 1:
                y_pp = torch.empty((NUM_KSPLIT, M, N), dtype=torch.float32, device=dev)
                y = torch.empty((M, N), dtype=torch.bfloat16, device=dev)
                _ws_cache[out_key] = (y_pp, y)
            else:
                y = torch.empty((M, N), dtype=torch.bfloat16, device=dev)
                _ws_cache[out_key] = (None, y)
        y_pp, y = _ws_cache[out_key]

        out_tensor = y if NUM_KSPLIT == 1 else y_pp

        grid = lambda META: (
            META["NUM_KSPLIT"]
            * triton.cdiv(M, META["BLOCK_SIZE_M"])
            * triton.cdiv(N, META["BLOCK_SIZE_N"]),
        )

        _gemm_fp4_kernel[grid](
            aq_buf, B_t, out_tensor,
            asc_buf, B_scale_sh_u8,
            M, N, K_packed,
            Ks_stride,
            aq_buf.stride(0), aq_buf.stride(1),
            B_t.stride(0), B_t.stride(1),
            0 if NUM_KSPLIT == 1 else y_pp.stride(0),
            out_tensor.stride(-2), out_tensor.stride(-1),
            asc_buf.stride(0), asc_buf.stride(1),
            SPLITK_BLOCK_SIZE=config["SPLITK_BLOCK_SIZE"],
            BLOCK_SIZE_M=config["BLOCK_SIZE_M"],
            BLOCK_SIZE_N=config["BLOCK_SIZE_N"],
            BLOCK_SIZE_K=config["BLOCK_SIZE_K"],
            GROUP_SIZE_M=config["GROUP_SIZE_M"],
            NUM_KSPLIT=NUM_KSPLIT,
            num_warps=config["num_warps"],
            num_stages=config["num_stages"],
            waves_per_eu=config["waves_per_eu"],
            matrix_instr_nonkdim=config["matrix_instr_nonkdim"],
            schedule_hint="attention",
            allow_flush_denorm=True,
        )

        if NUM_KSPLIT > 1:
            REDUCE_BLOCK_SIZE_M = 16
            REDUCE_BLOCK_SIZE_N = 16
            ACTUAL_KSPLIT = triton.cdiv(K_packed, (config["SPLITK_BLOCK_SIZE"] // 2))

            grid_reduce = (
                triton.cdiv(M, REDUCE_BLOCK_SIZE_M),
                triton.cdiv(N, REDUCE_BLOCK_SIZE_N),
            )
            _reduce_kernel[grid_reduce](
                y_pp, y,
                M, N,
                y_pp.stride(0), y_pp.stride(1), y_pp.stride(2),
                y.stride(0), y.stride(1),
                BLOCK_SIZE_M=REDUCE_BLOCK_SIZE_M,
                BLOCK_SIZE_N=REDUCE_BLOCK_SIZE_N,
                ACTUAL_KSPLIT=ACTUAL_KSPLIT,
                MAX_KSPLIT=triton.next_power_of_2(NUM_KSPLIT),
            )

        return y

    elif M >= 16 and K > 1024:
        # ================================================================
        # Triton FUSED path for M=16 K>1024 (inline BF16->FP4 quant)
        # Eliminates separate quant_a + fp32_to_bf16 kernels
        # ================================================================
        K_packed = K // 2
        dev = A.device

        # Get Triton config (uses M=16 entries)
        config = _get_triton_config(M, N, K)

        # Handle split-K
        if config["NUM_KSPLIT"] > 1:
            SPLITK_BLOCK_SIZE, BLOCK_SIZE_K, NUM_KSPLIT = _get_triton_splitk(
                K_packed, config["BLOCK_SIZE_K"], config["NUM_KSPLIT"]
            )
            config["SPLITK_BLOCK_SIZE"] = SPLITK_BLOCK_SIZE
            config["BLOCK_SIZE_K"] = BLOCK_SIZE_K
            config["NUM_KSPLIT"] = NUM_KSPLIT
        else:
            config["SPLITK_BLOCK_SIZE"] = 2 * K_packed

        if config["BLOCK_SIZE_K"] >= 2 * K_packed:
            config["BLOCK_SIZE_K"] = triton.next_power_of_2(2 * K_packed)
            config["SPLITK_BLOCK_SIZE"] = 2 * K_packed
            config["NUM_KSPLIT"] = 1

        config["BLOCK_SIZE_K"] = max(config["BLOCK_SIZE_K"], 128)

        NUM_KSPLIT = config["NUM_KSPLIT"]

        # B data for Triton (transposed layout)
        B_q_u8 = B_q.view(torch.uint8) if B_q.dtype != torch.uint8 else B_q
        B_t = B_q_u8.T
        B_scale_sh_u8 = B_scale_sh.view(torch.uint8) if B_scale_sh.dtype != torch.uint8 else B_scale_sh
        Ks_stride = B_scale_sh_u8.shape[1]

        # Output tensors
        out_key = ("fused", M, N, NUM_KSPLIT, dev)
        if out_key not in _ws_cache:
            if NUM_KSPLIT > 1:
                y_pp = torch.empty((NUM_KSPLIT, M, N), dtype=torch.float32, device=dev)
                y = torch.empty((M, N), dtype=torch.bfloat16, device=dev)
                _ws_cache[out_key] = (y_pp, y)
            else:
                y = torch.empty((M, N), dtype=torch.bfloat16, device=dev)
                _ws_cache[out_key] = (None, y)
        y_pp, y = _ws_cache[out_key]

        out_tensor = y if NUM_KSPLIT == 1 else y_pp

        grid = lambda META: (
            META["NUM_KSPLIT"]
            * triton.cdiv(M, META["BLOCK_SIZE_M"])
            * triton.cdiv(N, META["BLOCK_SIZE_N"]),
        )

        _fused_gemm_fp4_kernel[grid](
            A, B_t, out_tensor,
            B_scale_sh_u8,
            M, N, K_packed,
            K,
            Ks_stride,
            A.stride(0), A.stride(1),
            B_t.stride(0), B_t.stride(1),
            0 if NUM_KSPLIT == 1 else y_pp.stride(0),
            out_tensor.stride(-2), out_tensor.stride(-1),
            SPLITK_BLOCK_SIZE=config["SPLITK_BLOCK_SIZE"],
            BLOCK_SIZE_M=config["BLOCK_SIZE_M"],
            BLOCK_SIZE_N=config["BLOCK_SIZE_N"],
            BLOCK_SIZE_K=config["BLOCK_SIZE_K"],
            GROUP_SIZE_M=config["GROUP_SIZE_M"],
            NUM_KSPLIT=NUM_KSPLIT,
            num_warps=config["num_warps"],
            num_stages=config["num_stages"],
            waves_per_eu=config["waves_per_eu"],
            matrix_instr_nonkdim=config["matrix_instr_nonkdim"],
            schedule_hint="attention",
            allow_flush_denorm=True,
        )

        if NUM_KSPLIT > 1:
            REDUCE_BLOCK_SIZE_M = 16
            REDUCE_BLOCK_SIZE_N = 16
            ACTUAL_KSPLIT = triton.cdiv(K_packed, (config["SPLITK_BLOCK_SIZE"] // 2))

            grid_reduce = (
                triton.cdiv(M, REDUCE_BLOCK_SIZE_M),
                triton.cdiv(N, REDUCE_BLOCK_SIZE_N),
            )
            _reduce_kernel[grid_reduce](
                y_pp, y,
                M, N,
                y_pp.stride(0), y_pp.stride(1), y_pp.stride(2),
                y.stride(0), y.stride(1),
                BLOCK_SIZE_M=REDUCE_BLOCK_SIZE_M,
                BLOCK_SIZE_N=REDUCE_BLOCK_SIZE_N,
                ACTUAL_KSPLIT=ACTUAL_KSPLIT,
                MAX_KSPLIT=triton.next_power_of_2(NUM_KSPLIT),
            )

        return y

    else:
        # ================================================================
        # HIP C++ path for M<16 or (M<=32 and K<=1024) (proven 9.03us geomean)
        # ================================================================
        key = (M, K, N)
        dev = A.device
        if key not in _ws_cache:
            mp = ((M + 31) // 32) * 32
            sm = ((mp + 255) // 256) * 256
            _ws_cache[key] = (
                torch.zeros(M, N, dtype=torch.float32, device=dev),
                torch.empty(M, N, dtype=torch.bfloat16, device=dev),
                torch.empty(M, K // 2, dtype=torch.uint8, device=dev),
                torch.empty(sm, K // 32, dtype=torch.uint8, device=dev),
                torch.empty(mp, N, dtype=torch.bfloat16, device=dev),
            )
        fp32_ws, bf16_out, aq_buf, asc_buf, asm_out = _ws_cache[key]

        result = ext.dispatch_gemm(A, B_q, B_shuffle, B_scale_sh, N,
                                    fp32_ws, bf16_out, aq_buf, asc_buf, asm_out)
        return result
scrolls · 1032 lines total

Source code from GPU Mode and the KernelBot dataset · June 9 Researcher Reciprocity License v1.0

Best evidence level for this revision: reported

JSON