/**
 * Test fmha_6warp_tma_multirow_multitile — multi-row + multi-tile KV + in-kernel rescale.
 */

#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;
constexpr int MY_MMA_K = 16;
constexpr int TILE_SZ = 128 * MY_MMA_K;
constexpr int HD_CHUNK = (HD <= 256 ? HD : 256);

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

static size_t compute_smem() {
    size_t off = 0;
    off += 4; off = (off+127)&~(size_t)127;
    off += 16; off = (off+127)&~(size_t)127;
    off += TILE_SZ * 2; off = (off+127)&~(size_t)127;  // sTmaBuf
    off += TILE_SZ * 2; off = (off+127)&~(size_t)127;  // sQ0
    off += TILE_SZ * 2; off = (off+127)&~(size_t)127;  // sK0
    off += TILE_SZ * 2; off = (off+127)&~(size_t)127;  // sPk
    off += 16 * MY_MMA_K * 2;                            // sV
    off = (off+127)&~(size_t)127;
    off += MAX_T * HD_CHUNK * 4;                          // sOacc (chunk-sized)
    off += MAX_T * 4;                                     // sRunningMax
    off += MAX_T * 4;                                     // sRunningSum
    off += MAX_T * 4;                                     // sTileRowMax
    off += MAX_T * 4;                                     // sTileRowSum
    return off;
}

static void reference_attention(
    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[1024];
        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;
    }
}

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

    bf16_t* h_q = (bf16_t*)calloc(total_heads * MAX_T * HD, sizeof(bf16_t));
    bf16_t* h_k = (bf16_t*)calloc(total_heads * s_k * HD, sizeof(bf16_t));
    bf16_t* h_v = (bf16_t*)calloc(total_heads * HD * s_k, 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);
    for (int h = 0; h < total_heads; h++) {
        for (int i = 0; i < T*HD; i++) h_q[h*MAX_T*HD+i] = f32_to_bf16_host((float)(rand()%100)/100.0f-0.5f);
        for (int i = 0; i < s_k*HD; i++) h_k[h*s_k*HD+i] = f32_to_bf16_host((float)(rand()%100)/100.0f-0.5f);
        for (int i = 0; i < HD*s_k; i++) h_v[h*HD*s_k+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 * MAX_T * HD * sizeof(bf16_t));
    cudaMalloc(&d_k, total_heads * s_k * HD * sizeof(bf16_t));
    cudaMalloc(&d_v, total_heads * HD * s_k * sizeof(bf16_t));
    cudaMalloc(&d_o, total_heads * MAX_T * HD * sizeof(bf16_t));
    cudaMalloc(&d_lse, total_heads * MAX_T * sizeof(float));
    printf("  cudaMalloc OK\n"); fflush(stdout);
    cudaMemcpy(d_q, h_q, total_heads * MAX_T * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);
    cudaMemcpy(d_k, h_k, total_heads * s_k * HD * sizeof(bf16_t), cudaMemcpyHostToDevice);
    cudaMemcpy(d_v, h_v, total_heads * HD * s_k * sizeof(bf16_t), cudaMemcpyHostToDevice);
    cudaMemset(d_o, 0, total_heads * MAX_T * HD * sizeof(bf16_t));
    cudaMemset(d_lse, 0, total_heads * MAX_T * sizeof(float));

    // TMA descriptors for K: (s_k, HD) tile (128, 16)
    CUtensorMap* tma_k_arr = (CUtensorMap*)malloc(total_heads * sizeof(CUtensorMap));
    CUtensorMap* d_tma_k;
    cudaMalloc(&d_tma_k, total_heads * sizeof(CUtensorMap));
    for (int h = 0; h < total_heads; h++) {
        create_tma_desc_2d_bf16(&tma_k_arr[h], d_k + h * s_k * HD, s_k, HD, 128, 16);
    }
    cudaMemcpy(d_tma_k, tma_k_arr, total_heads * sizeof(CUtensorMap), cudaMemcpyHostToDevice);

    // TMA descriptors for V: (HD, s_k) tile (16, 16)
    CUtensorMap* tma_v_arr = (CUtensorMap*)malloc(total_heads * sizeof(CUtensorMap));
    CUtensorMap* d_tma_v;
    cudaMalloc(&d_tma_v, total_heads * sizeof(CUtensorMap));
    for (int h = 0; h < total_heads; h++) {
        create_tma_desc_2d_bf16(&tma_v_arr[h], d_v + h * HD * s_k, HD, s_k, 16, 16);
    }
    cudaMemcpy(d_tma_v, tma_v_arr, total_heads * sizeof(CUtensorMap), cudaMemcpyHostToDevice);

    FmhaTmaMultiRowMultiTileParams params;
    params.q = d_q;
    params.tma_k = d_tma_k;
    params.tma_v = d_tma_v;
    params.o = d_o;
    params.lse = d_lse;
    params.s_k = s_k;
    params.T = T;
    params.scale = SCALE;
    params.n_h = n_h;
    params.q_head_stride = MAX_T * HD;
    params.q_batch_stride = n_h * MAX_T * HD;
    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;

    size_t smem = compute_smem();
    printf("  SMEM: %zu bytes (%.1f KB)\n", smem, smem / 1024.0); fflush(stdout);
    if (smem > 48 * 1024) {
        cudaError_t sae = cudaFuncSetAttribute(fmha_6warp_tma_multirow_multitile_kernel<HD>,
                             cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem);
        printf("  cudaFuncSetAttribute: %s\n", cudaGetErrorString(sae)); fflush(stdout);
    }

    dim3 grid(1, n_h, batch);
    printf("  Launching kernel: grid=(%d,%d,%d) smem=%zu\n", grid.x, grid.y, grid.z, smem); fflush(stdout);
    fmha_6warp_tma_multirow_multitile_kernel<HD><<<grid, 192, smem>>>(params);
    printf("  Kernel launched.\n");

    cudaError_t lerr = cudaGetLastError();
    if (lerr != cudaSuccess) {
        printf("  LAUNCH ERROR: %s\n", cudaGetErrorString(lerr));
        return 1;
    }
    cudaError_t err = cudaDeviceSynchronize();
    if (err != cudaSuccess) {
        printf("  CUDA ERROR: %s\n", cudaGetErrorString(err));
        return 1;
    }
    printf("  Kernel completed OK.\n");

    cudaMemcpy(h_o, d_o, total_heads * MAX_T * HD * sizeof(bf16_t), cudaMemcpyDeviceToHost);
    cudaMemcpy(h_lse, d_lse, total_heads * MAX_T * sizeof(float), cudaMemcpyDeviceToHost);

    int total_bad = 0;
    float min_cos = 1.0f;
    for (int h = 0; h < total_heads; h++) {
        float* o_ref = (float*)calloc(T * HD, sizeof(float));
        reference_attention(
            h_q + h * MAX_T * HD, h_k + h * s_k * HD, h_v + h * HD * s_k,
            o_ref, nullptr, HD, T, s_k, SCALE);

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

    cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_o); cudaFree(d_lse);
    cudaFree(d_tma_k); cudaFree(d_tma_v);
    free(h_q); free(h_k); free(h_v); free(h_o); free(h_lse);
    free(tma_k_arr); free(tma_v_arr);

    return min_cos > 0.999f ? 0 : 1;
}

int main() {
    setbuf(stdout, NULL);
    printf("START: test_fmha_6warp_tma_multirow_multitile HD=%d\n", HD);
    int total_fail = 0;

    printf("\n=== 6-warp TMA FMHA multi-row multi-tile HD=%d ===\n", HD);

    // Single KV tile (s_k=128, baseline)
    for (int T : {1, 4, 32, 128}) {
        total_fail += test_single(T, 128);
    }

    // Multi-tile KV — the whole point of D1.5
    for (int s_k : {256, 384, 512}) {
        for (int T : {1, 4, 32, 128}) {
            total_fail += test_single(T, s_k);
        }
    }

    // Multi-head + batch
    total_fail += test_single(4, 256, 4, 1);   // n_h=4
    total_fail += test_single(4, 256, 2, 2);   // n_h=2, batch=2

    printf("\nOverall: %s\n", total_fail == 0 ? "ALL PASSED" : "SOME FAILED");
    return total_fail == 0 ? 0 : 1;
}
