/**
 * TMA + QK — test if the mbarrier wait in multi-warp is the issue.
 * Approach: only thread 0 issues TMA AND waits, then __syncthreads().
 * All other threads skip the mbarrier entirely.
 */

#include <cuda_runtime.h>
#include <cuda.h>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>

#ifndef HD_VAL
#define HD_VAL 64
#endif

typedef unsigned short bf16_t;
static bf16_t f32_to_bf16_host(float f) { uint32_t u; memcpy(&u,&f,4); return (uint16_t)(u>>16); }
static float bf16_to_f32_host(bf16_t h) { uint32_t u=(uint32_t)h<<16; float f; memcpy(&f,&u,4); return f; }

constexpr int HD = HD_VAL;
constexpr int SK = 128;
constexpr int MMA_K = 16;
constexpr int BLOCK_MN = 128;
constexpr int TILE_SZ = 128 * MMA_K;
constexpr int TMEM_N = (HD <= 128) ? 128 : 256;
constexpr int NKT = HD / MMA_K;
constexpr int CORES_MN = 16;
constexpr int NUM_READS = SK / 8;

__device__ __forceinline__ void tma_mbarrier_init(uint32_t smem_mbar, uint32_t count) {
    asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" :: "r"(smem_mbar), "r"(count));
}
__device__ __forceinline__ void tma_mbarrier_arrive_expect_tx(uint32_t smem_mbar, uint32_t tx_bytes) {
    asm volatile("mbarrier.arrive.expect_tx.release.cta.shared::cta.b64 _, [%0], %1;"
        :: "r"(smem_mbar), "r"(tx_bytes) : "memory");
}
__device__ __forceinline__ void tma_load_2d(uint32_t dst, uint64_t desc, uint32_t mbar, int cx, int cy) {
    asm volatile("cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes "
        "[%0], [%1, {%3, %4}], [%2];" :: "r"(dst), "l"(desc), "r"(mbar), "r"(cx), "r"(cy) : "memory");
}
__device__ __forceinline__ void tma_mbarrier_wait(uint32_t smem_mbar, int phase) {
    asm volatile("{\n\t.reg .pred P1;\n\tLAB_WAIT:mbarrier.try_wait.parity.acquire.cta.shared::cta.b64 P1, [%0], %1, %2;\n\t@P1 bra.uni DONE;\n\tbra.uni LAB_WAIT;\n\tDONE:\n\t}" :: "r"(smem_mbar), "r"(phase), "r"(0x989680) : "memory");
}

__device__ __forceinline__ bf16_t f32_to_bf16(float f) { bf16_t h; asm("cvt.rn.bf16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; }
__device__ __forceinline__ float bf16_to_f32(bf16_t h) { float f; asm("cvt.f32.bf16 %0, %1;" : "=f"(f) : "h"(h)); return f; }

__device__ void tmem_alloc(uint32_t smem_ptr, int n) {
    asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" :: "r"(smem_ptr), "r"(n));
}
__device__ void tmem_dealloc(uint32_t tmem_ptr, int n) {
    asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" :: "r"(tmem_ptr), "r"(n));
}

__device__ __forceinline__ uint64_t desc_encode(uint64_t b) { return b >> 4; }
__device__ __forceinline__ uint64_t make_umma_desc_kmajor_none(uint32_t smem_addr, int block_mn) {
    uint64_t d = 0;
    d |= desc_encode(smem_addr) & 0x3FFF;
    d |= (desc_encode(block_mn * 16) & 0x3FFF) << 16;
    d |= (desc_encode(128) & 0x3FFF) << 32;
    d |= 1ULL << 46;
    return d;
}
__device__ __forceinline__ uint32_t make_idesc(int bm, int bn) {
    return (1U<<4)|(1U<<7)|(1U<<10)|((uint32_t)(bn>>3)<<17)|((uint32_t)(bm>>4)<<24);
}
__device__ void umma_ss_f16(uint32_t tc, uint64_t da, uint64_t db, uint32_t idesc, bool acc) {
    uint32_t sb = acc ? 0x3F800000u : 0u;
    asm volatile("{\n\t.reg .pred p;\n\tsetp.ne.b32 p, %4, 0;\n\ttcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, {%5, %6, %7, %8}, p;\n\t}"
        :: "r"(tc), "l"(da), "l"(db), "r"(idesc), "r"(sb), "r"(0), "r"(0), "r"(0), "r"(0));
}

// Test A: TMA + mbarrier, ALL threads wait (original failing pattern)
__global__ void __launch_bounds__(128)
test_a_mbarrier_allwait(
    float* out_s, const bf16_t* q, CUtensorMap* tma_k, int s_k
) {
    const int tid = threadIdx.x;
    const int wid = tid / 32, lane = tid % 32;

    extern __shared__ __align__(128) char sbuf[];
    size_t off = 0;
    uint32_t* sTmemBase = (uint32_t*)(sbuf + off); off = 4;
    off = (off + 127) & ~(size_t)127;
    bf16_t* sQ0 = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;
    bf16_t* sK0 = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;
    bf16_t* sTmaBuf = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;
    off = (off + 15) & ~(size_t)15;
    uint64_t* sMbar = (uint64_t*)(sbuf + off); off += 8;

    if (wid == 1) tmem_alloc(__cvta_generic_to_shared(sTmemBase), TMEM_N);
    if (tid == 0) { tma_mbarrier_init((uint32_t)__cvta_generic_to_shared(sMbar), 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); }
    __syncthreads();
    uint32_t tb = *sTmemBase;
    uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar);
    int phase = 0;

    uint32_t idesc = make_idesc(BLOCK_MN, BLOCK_MN);
    for (int kt = 0; kt < NKT; kt++) {
        // Q: direct load
        for (int i = tid; i < TILE_SZ; i += 128) sQ0[i] = 0;
        for (int d = tid; d < MMA_K; d += 128) {
            int fd = kt * MMA_K + d;
            if (fd < HD) { int ck = d/8, lc = d%8; sQ0[ck*CORES_MN*64+lc] = q[fd]; }
        }
        __syncthreads();

        // K: TMA, ALL threads wait
        if (tid == 0) {
            tma_load_2d((uint32_t)__cvta_generic_to_shared(sTmaBuf), (uint64_t)tma_k, mbar_addr, kt*MMA_K, 0);
            tma_mbarrier_arrive_expect_tx(mbar_addr, TILE_SZ * sizeof(bf16_t));
        }
        tma_mbarrier_wait(mbar_addr, phase); phase ^= 1;
        __syncthreads();

        // canonical write
        for (int i = tid; i < TILE_SZ; i += 128) sK0[i] = 0;
        for (int i = tid; i < s_k * MMA_K; i += 128) {
            int r = i / MMA_K, c = i % MMA_K;
            sK0[(c/8)*CORES_MN*64 + (r/8)*64 + (r%8)*8 + c%8] = sTmaBuf[i];
        }
        __syncthreads();

        // MMA
        if (tid == 0) {
            umma_ss_f16(tb, make_umma_desc_kmajor_none(__cvta_generic_to_shared(sQ0), BLOCK_MN),
                         make_umma_desc_kmajor_none(__cvta_generic_to_shared(sK0), BLOCK_MN), idesc, kt > 0);
            asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
        }
        __syncthreads();
    }
    asm volatile("fence.sc.gpu;" ::: "memory"); __syncthreads();

    // Read S
    if (wid == 0) {
        for (int n = 0; n < NUM_READS; n++) {
            float tmp[8];
            asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7},[%8];"
                : "=f"(tmp[0]),"=f"(tmp[1]),"=f"(tmp[2]),"=f"(tmp[3]),
                  "=f"(tmp[4]),"=f"(tmp[5]),"=f"(tmp[6]),"=f"(tmp[7])
                : "r"(tb + n * 8));
            asm volatile("tcgen05.wait::ld.sync.aligned;");
            if (lane == 0) for (int c=0;c<8;c++) { int col=n*8+c; if(col<s_k) out_s[col]=tmp[c]; }
        }
    }
    __syncthreads();
    if (wid == 0) tmem_dealloc(tb, TMEM_N);
}

// Test B: TMA, only tid==0 issues+waits, others just __syncthreads()
__global__ void __launch_bounds__(128)
test_b_mbarrier_tid0wait(
    float* out_s, const bf16_t* q, CUtensorMap* tma_k, int s_k
) {
    const int tid = threadIdx.x;
    const int wid = tid / 32, lane = tid % 32;

    extern __shared__ __align__(128) char sbuf[];
    size_t off = 0;
    uint32_t* sTmemBase = (uint32_t*)(sbuf + off); off = 4;
    off = (off + 127) & ~(size_t)127;
    bf16_t* sQ0 = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;
    bf16_t* sK0 = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;
    bf16_t* sTmaBuf = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;
    off = (off + 15) & ~(size_t)15;
    uint64_t* sMbar = (uint64_t*)(sbuf + off); off += 8;

    if (wid == 1) tmem_alloc(__cvta_generic_to_shared(sTmemBase), TMEM_N);
    if (tid == 0) { tma_mbarrier_init((uint32_t)__cvta_generic_to_shared(sMbar), 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); }
    __syncthreads();
    uint32_t tb = *sTmemBase;
    uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar);

    uint32_t idesc = make_idesc(BLOCK_MN, BLOCK_MN);
    for (int kt = 0; kt < NKT; kt++) {
        // Q: direct load
        for (int i = tid; i < TILE_SZ; i += 128) sQ0[i] = 0;
        for (int d = tid; d < MMA_K; d += 128) {
            int fd = kt * MMA_K + d;
            if (fd < HD) { int ck = d/8, lc = d%8; sQ0[ck*CORES_MN*64+lc] = q[fd]; }
        }
        __syncthreads();

        // K: TMA — only tid==0 issues AND waits
        if (tid == 0) {
            tma_load_2d((uint32_t)__cvta_generic_to_shared(sTmaBuf), (uint64_t)tma_k, mbar_addr, kt*MMA_K, 0);
            tma_mbarrier_arrive_expect_tx(mbar_addr, TILE_SZ * sizeof(bf16_t));
            tma_mbarrier_wait(mbar_addr, 0);  // phase=0, only called once
        }
        // ALL threads sync after TMA completes
        __syncthreads();

        // Re-init mbarrier for next use
        if (tid == 0) {
            tma_mbarrier_init(mbar_addr, 1);
            asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory");
        }
        __syncthreads();

        // canonical write
        for (int i = tid; i < TILE_SZ; i += 128) sK0[i] = 0;
        for (int i = tid; i < s_k * MMA_K; i += 128) {
            int r = i / MMA_K, c = i % MMA_K;
            sK0[(c/8)*CORES_MN*64 + (r/8)*64 + (r%8)*8 + c%8] = sTmaBuf[i];
        }
        __syncthreads();

        // MMA
        if (tid == 0) {
            umma_ss_f16(tb, make_umma_desc_kmajor_none(__cvta_generic_to_shared(sQ0), BLOCK_MN),
                         make_umma_desc_kmajor_none(__cvta_generic_to_shared(sK0), BLOCK_MN), idesc, kt > 0);
            asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
        }
        __syncthreads();
    }
    asm volatile("fence.sc.gpu;" ::: "memory"); __syncthreads();

    if (wid == 0) {
        for (int n = 0; n < NUM_READS; n++) {
            float tmp[8];
            asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7},[%8];"
                : "=f"(tmp[0]),"=f"(tmp[1]),"=f"(tmp[2]),"=f"(tmp[3]),
                  "=f"(tmp[4]),"=f"(tmp[5]),"=f"(tmp[6]),"=f"(tmp[7])
                : "r"(tb + n * 8));
            asm volatile("tcgen05.wait::ld.sync.aligned;");
            if (lane == 0) for (int c=0;c<8;c++) { int col=n*8+c; if(col<s_k) out_s[col]=tmp[c]; }
        }
    }
    __syncthreads();
    if (wid == 0) tmem_dealloc(tb, TMEM_N);
}

// Test C: NO TMA at all, direct GMEM load (should work — same as test_fmha_gen)
__global__ void __launch_bounds__(128)
test_c_direct_load(
    float* out_s, const bf16_t* q, const bf16_t* k, int s_k
) {
    const int tid = threadIdx.x;
    const int wid = tid / 32, lane = tid % 32;

    extern __shared__ __align__(128) char sbuf[];
    size_t off = 0;
    uint32_t* sTmemBase = (uint32_t*)(sbuf + off); off = 4;
    off = (off + 127) & ~(size_t)127;
    bf16_t* sQ0 = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;
    bf16_t* sK0 = (bf16_t*)(sbuf + off); off += TILE_SZ * 2;

    if (wid == 1) tmem_alloc(__cvta_generic_to_shared(sTmemBase), TMEM_N);
    __syncthreads();
    uint32_t tb = *sTmemBase;

    uint32_t idesc = make_idesc(BLOCK_MN, BLOCK_MN);
    for (int kt = 0; kt < NKT; kt++) {
        // Q: direct
        for (int i = tid; i < TILE_SZ; i += 128) sQ0[i] = 0;
        for (int d = tid; d < MMA_K; d += 128) {
            int fd = kt * MMA_K + d;
            if (fd < HD) { int ck = d/8, lc = d%8; sQ0[ck*CORES_MN*64+lc] = q[fd]; }
        }
        // K: direct
        for (int i = tid; i < TILE_SZ; i += 128) sK0[i] = 0;
        for (int i = tid; i < s_k * MMA_K; i += 128) {
            int r = i / MMA_K, c = i % MMA_K;
            sK0[(c/8)*CORES_MN*64 + (r/8)*64 + (r%8)*8 + c%8] = k[r*HD + kt*MMA_K + c];
        }
        __syncthreads();

        if (tid == 0) {
            umma_ss_f16(tb, make_umma_desc_kmajor_none(__cvta_generic_to_shared(sQ0), BLOCK_MN),
                         make_umma_desc_kmajor_none(__cvta_generic_to_shared(sK0), BLOCK_MN), idesc, kt > 0);
            asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
        }
        __syncthreads();
    }
    asm volatile("fence.sc.gpu;" ::: "memory"); __syncthreads();

    if (wid == 0) {
        for (int n = 0; n < NUM_READS; n++) {
            float tmp[8];
            asm volatile("tcgen05.ld.sync.aligned.32x32b.x8.b32 {%0,%1,%2,%3,%4,%5,%6,%7},[%8];"
                : "=f"(tmp[0]),"=f"(tmp[1]),"=f"(tmp[2]),"=f"(tmp[3]),
                  "=f"(tmp[4]),"=f"(tmp[5]),"=f"(tmp[6]),"=f"(tmp[7])
                : "r"(tb + n * 8));
            asm volatile("tcgen05.wait::ld.sync.aligned;");
            if (lane == 0) for (int c=0;c<8;c++) { int col=n*8+c; if(col<s_k) out_s[col]=tmp[c]; }
        }
    }
    __syncthreads();
    if (wid == 0) tmem_dealloc(tb, TMEM_N);
}

inline bool create_tma_desc_2d_bf16(CUtensorMap* out, const void* ptr, uint64_t rows, uint64_t cols, uint32_t tr, uint32_t tc) {
    uint64_t gd[]={cols,rows}, gs[]={cols*2}; uint32_t td[]={tc,tr}, ts[]={1,1};
    CUresult r = cuTensorMapEncodeTiled(out, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast<void*>(ptr), gd, gs, td, ts,
        CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE);
    if (r!=CUDA_SUCCESS) { fprintf(stderr,"TMA fail %d\n",(int)r); return false; }
    int dv=0; cudaDriverGetVersion(&dv);
    if (dv<=13010 && rows*cols*2<131072) reinterpret_cast<uint64_t*>(out)[1] &= ~(1ULL<<21);
    return true;
}

int main() {
    printf("=== TMA QK diagnostic (HD=%d) ===\n", HD);
    bf16_t* h_q = (bf16_t*)calloc(HD, sizeof(bf16_t));
    bf16_t* h_k = (bf16_t*)calloc(SK*HD, sizeof(bf16_t));
    srand(42);
    for (int i=0;i<HD;i++) h_q[i]=f32_to_bf16_host((float)(rand()%100)/100.0f-0.5f);
    for (int i=0;i<SK*HD;i++) h_k[i]=f32_to_bf16_host((float)(rand()%100)/100.0f-0.5f);

    bf16_t *d_q,*d_k; float *d_out;
    cudaMalloc(&d_q, HD*2); cudaMalloc(&d_k, SK*HD*2); cudaMalloc(&d_out, SK*4);
    cudaMemcpy(d_q, h_q, HD*2, cudaMemcpyHostToDevice);
    cudaMemcpy(d_k, h_k, SK*HD*2, cudaMemcpyHostToDevice);

    CUtensorMap tma_k; CUtensorMap* d_tma_k;
    create_tma_desc_2d_bf16(&tma_k, d_k, SK, HD, 128, MMA_K);
    cudaMalloc(&d_tma_k, sizeof(CUtensorMap));
    cudaMemcpy(d_tma_k, &tma_k, sizeof(CUtensorMap), cudaMemcpyHostToDevice);

    // Reference
    float s_ref[SK];
    for (int j=0;j<SK;j++) { float d=0; for (int dd=0;dd<HD;dd++) d+=bf16_to_f32_host(h_q[dd])*bf16_to_f32_host(h_k[j*HD+dd]); s_ref[j]=d; }

    size_t smem_a = 4+128+TILE_SZ*3*2+16+8+256;
    size_t smem_c = 4+128+TILE_SZ*2*2+256;

    auto check = [&](const char* name, cudaError_t err) {
        if (err != cudaSuccess) { printf("  %s: CUDA ERROR: %s\n", name, cudaGetErrorString(err)); return; }
        float* h = (float*)malloc(SK*4);
        cudaMemcpy(h, d_out, SK*4, cudaMemcpyDeviceToHost);
        int bad=0; float mr=0;
        for (int j=0;j<SK;j++) {
            float rel = fabsf(s_ref[j])>1e-4f ? fabsf(h[j]-s_ref[j])/fabsf(s_ref[j]) : fabsf(h[j]-s_ref[j]);
            if (rel>mr) mr=rel;
            if (rel>0.01f) bad++;
        }
        printf("  %s: max_rel=%.8f bad=%d %s\n", name, mr, bad, bad==0?"PASS":"FAIL");
        free(h);
    };

    // Test A: mbarrier, all wait
    printf("Test A: mbarrier all-wait\n");
    cudaMemset(d_out, 0, SK*4);
    cudaFuncSetAttribute(test_a_mbarrier_allwait, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_a);
    test_a_mbarrier_allwait<<<1,128,smem_a>>>(d_out, d_q, d_tma_k, SK);
    check("A", cudaDeviceSynchronize());

    // Test B: mbarrier, tid0 only wait
    printf("Test B: mbarrier tid0-wait\n");
    cudaMemset(d_out, 0, SK*4);
    cudaFuncSetAttribute(test_b_mbarrier_tid0wait, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_a);
    test_b_mbarrier_tid0wait<<<1,128,smem_a>>>(d_out, d_q, d_tma_k, SK);
    check("B", cudaDeviceSynchronize());

    // Test C: direct load (baseline)
    printf("Test C: direct load (no TMA)\n");
    cudaMemset(d_out, 0, SK*4);
    cudaFuncSetAttribute(test_c_direct_load, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem_c);
    test_c_direct_load<<<1,128,smem_c>>>(d_out, d_q, d_k, SK);
    check("C", cudaDeviceSynchronize());

    cudaFree(d_q); cudaFree(d_k); cudaFree(d_out); cudaFree(d_tma_k);
    free(h_q); free(h_k);
    return 0;
}
