/**
 * Test TMA FMHA kernel (4-warp, TMA async loads for K and V).
 * Based on the proven test_fmha_gen pattern.
 */

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

#ifndef HD_VAL
#define HD_VAL 64
#endif

#include "dsv4/kernels/attention/fmha_common.cuh"
#include "dsv4/kernels/attention/fmha_umma_desc.cuh"
#include "dsv4/kernels/attention/fmha_tma.cuh"

using namespace dsv4::kernels::attention;

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 MAX_T = 128;

#include "dsv4/kernels/attention/fmha_6warp_tma.cuh"

static size_t compute_smem_tma() {
    size_t off = 0;
    off += 4;                           // sTmemBase
    off = (off + 127) & ~(size_t)127;
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);   // sQ0
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);   // sK0
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);   // sTmaBuf
    off += 8;                                     // sMbar
    off += MAX_T * sizeof(float);                 // sRowMax
    off += MAX_T * sizeof(float);                 // sRowSum
    off = (off + 127) & ~(size_t)127;
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);   // sPk
    off += 128 * MMA_K_BF16 * sizeof(bf16_t);   // sV
    return off;
}

static void reference_attention_multirow(
    const bf16_t* q, const bf16_t* k, const bf16_t* v,
    float* o_ref, float* lse_ref,
    int hd, int T, int s_k, float scale
) {
    for (int t = 0; t < T; t++) {
        float s[512];
        for (int j = 0; j < s_k; j++) {
            float dot = 0.0f;
            for (int d = 0; d < hd; d++)
                dot += bf16_to_f32_host(q[t * hd + d]) * bf16_to_f32_host(k[j * hd + d]);
            s[j] = dot * scale;
        }
        float mx = -INFINITY;
        for (int j = 0; j < s_k; j++) mx = fmaxf(mx, s[j]);
        float sm = 0.0f;
        for (int j = 0; j < s_k; j++) { s[j] = expf(s[j] - mx); sm += s[j]; }
        for (int j = 0; j < s_k; j++) s[j] /= sm;
        for (int d = 0; d < hd; d++) {
            float ov = 0.0f;
            for (int j = 0; j < s_k; j++) ov += s[j] * bf16_to_f32_host(v[d * s_k + j]);
            o_ref[t * hd + d] = ov;
        }
        if (lse_ref) lse_ref[t] = logf(sm) + mx;
    }
}

struct TmaDescSet {
    CUtensorMap tma_k, tma_v;
    CUtensorMap *d_tma_k, *d_tma_v;

    bool create(bf16_t* d_k, bf16_t* d_v, int s_k, int hd) {
        if (!create_tma_desc_2d_bf16(&tma_k, d_k, (uint64_t)s_k, (uint64_t)hd, 128, 16)) {
            printf("  K TMA desc FAILED\n"); return false;
        }
        // V: (HD, s_k), tile (16, 128) — rows=HD, cols=s_k
        if (!create_tma_desc_2d_bf16(&tma_v, d_v, (uint64_t)hd, (uint64_t)s_k, 16, 128)) {
            printf("  V TMA desc FAILED\n"); return false;
        }
        cudaMalloc(&d_tma_k, sizeof(CUtensorMap));
        cudaMalloc(&d_tma_v, sizeof(CUtensorMap));
        cudaMemcpy(d_tma_k, &tma_k, sizeof(CUtensorMap), cudaMemcpyHostToDevice);
        cudaMemcpy(d_tma_v, &tma_v, sizeof(CUtensorMap), cudaMemcpyHostToDevice);
        return true;
    }
    void destroy() {
        if (d_tma_k) { cudaFree(d_tma_k); d_tma_k = nullptr; }
        if (d_tma_v) { cudaFree(d_tma_v); d_tma_v = nullptr; }
    }
};

static int test_single(int T, int n_h = 1, int batch = 1) {
    printf("\n=== TMA T=%d, n_h=%d, batch=%d, HD=%d ===\n", T, n_h, batch, HD);
    const float SCALE = 1.0f / sqrtf((float)HD);
    int total_heads = batch * n_h;
    constexpr int Q_PAD = 128;

    bf16_t* h_q = (bf16_t*)calloc(total_heads * Q_PAD * HD, sizeof(bf16_t));
    bf16_t* h_k = (bf16_t*)malloc(total_heads * SK * HD * sizeof(bf16_t));
    bf16_t* h_v = (bf16_t*)malloc(total_heads * HD * SK * sizeof(bf16_t));
    bf16_t* h_o = (bf16_t*)calloc(total_heads * MAX_T * HD, sizeof(bf16_t));
    float* h_lse = (float*)calloc(total_heads * MAX_T, sizeof(float));

    srand(42 + T);
    for (int i = 0; i < total_heads * T * HD; i++) h_q[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);
    for (int i = 0; i < total_heads * SK * HD; i++) h_k[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);
    for (int i = 0; i < total_heads * HD * SK; i++) h_v[i] = f32_to_bf16_host((float)(rand()%100)/100.0f - 0.5f);

    bf16_t *d_q, *d_k, *d_v, *d_o; float *d_lse;
    cudaMalloc(&d_q, total_heads * Q_PAD * HD * sizeof(bf16_t));
    cudaMalloc(&d_k, total_heads * SK * HD * sizeof(bf16_t));
    cudaMalloc(&d_v, total_heads * HD * SK * sizeof(bf16_t));
    cudaMalloc(&d_o, total_heads * MAX_T * HD * sizeof(bf16_t));
    cudaMalloc(&d_lse, total_heads * MAX_T * sizeof(float));
    cudaMemcpy(d_q, h_q, total_heads * Q_PAD * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);
    cudaMemcpy(d_k, h_k, total_heads * SK * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);
    cudaMemcpy(d_v, h_v, total_heads * HD * SK * sizeof(bf16_t), cudaMemcpyHostToDevice);

    int failed = 0;
    float min_cos = 1.0f;

    for (int b = 0; b < batch; b++) {
        for (int h = 0; h < n_h; h++) {
            int idx = b * n_h + h;
            TmaDescSet tma;
            bf16_t* d_q_h = d_q + idx * Q_PAD * HD;
            bf16_t* d_k_h = d_k + idx * SK * HD;
            bf16_t* d_v_h = d_v + idx * HD * SK;
            if (!tma.create(d_k_h, d_v_h, SK, HD)) {
                failed++; continue;
            }

            FmhaTmaParams params;
            params.q = d_q_h; params.k = d_k_h; params.v = d_v_h;
            params.o = d_o + idx * MAX_T * HD; params.lse = d_lse + idx * MAX_T;
            params.s_k = SK; params.T = T; params.scale = SCALE; params.head_dim = HD;
            params.q_head_stride = Q_PAD * HD; params.q_batch_stride = n_h * Q_PAD * HD;
            params.k_head_stride = SK * HD; params.k_batch_stride = n_h * SK * HD;
            params.v_head_stride = HD * SK; params.v_batch_stride = n_h * HD * SK;
            params.o_head_stride = MAX_T * HD; params.o_batch_stride = n_h * MAX_T * HD;
            params.lse_head_stride = MAX_T; params.lse_batch_stride = n_h * MAX_T;
            params.tma_k = tma.d_tma_k; params.tma_v = tma.d_tma_v;

            int smem = (int)compute_smem_tma();
            cudaFuncSetAttribute(fmha_tma_kernel<HD>, cudaFuncAttributeMaxDynamicSharedMemorySize, smem);

            fmha_tma_kernel<HD><<<dim3(1,1,1), 128, smem>>>(params);
            cudaError_t err = cudaDeviceSynchronize();
            if (err != cudaSuccess) {
                printf("  CUDA ERROR b=%d h=%d: %s\n", b, h, cudaGetErrorString(err));
                failed++; tma.destroy(); continue;
            }

            bf16_t* h_o_head = (bf16_t*)malloc(T * HD * sizeof(bf16_t));
            cudaMemcpy(h_o_head, d_o + idx * MAX_T * HD, T * HD * sizeof(bf16_t), cudaMemcpyDeviceToHost);

            float o_ref[MAX_T * 512];
            reference_attention_multirow(h_q + idx * Q_PAD * HD, h_k + idx * SK * HD, h_v + idx * HD * SK, o_ref, nullptr, HD, T, SK, SCALE);

            for (int t = 0; t < T; t++) {
                float cs=0,na=0,nb=0;
                for (int d=0;d<HD;d++) {
                    float a=bf16_to_f32_host(h_o_head[t*HD+d]), b2=o_ref[t*HD+d];
                    if(fabsf(b2)>1e-4f){cs+=a*b2;na+=a*a;nb+=b2*b2;}
                }
                cs /= (sqrtf(na)*sqrtf(nb)+1e-10f);
                if(cs<min_cos) min_cos=cs;
                if(cs<0.999f) { printf("  FAIL b=%d h=%d t=%d cos=%.6f\n",b,h,t,cs); failed++; }
            }
            free(h_o_head);
            tma.destroy();
        }
    }
    printf("  min_cos=%.8f %s\n", min_cos, failed==0?"PASSED":"FAILED");

    cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_o); cudaFree(d_lse);
    free(h_q); free(h_k); free(h_v); free(h_o); free(h_lse);
    return failed == 0;
}

int main() {
    printf("TMA FMHA test (HD=%d)\n", HD);
    int ok = 1;
    ok &= test_single(1);
    ok &= test_single(4);
    ok &= test_single(32);
    ok &= test_single(64);
    ok &= test_single(128);
    printf("\n%s\n", ok ? "ALL PASSED" : "SOME FAILED");
    return ok ? 0 : 1;
}
