From 696462f07ab62823a47af7f3068965de6ca1588e Mon Sep 17 00:00:00 2001 From: biondizzle Date: Fri, 29 May 2026 04:36:52 +0000 Subject: [PATCH] feat: TMA async load infrastructure for FMHA kernel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fmha_tma.cuh: TMA descriptor creation, mbarrier helpers, cp.async.bulk.tensor.2d wrappers - fmha_6warp_tma.cuh: TMA-integrated multirow kernel with async GMEM→SMEM loads - TMA loads Q, K, V tiles to row-major SMEM - Transposes to canonical K-major layout for MMA - Same softmax/epilogue as non-TMA kernel - test_fmha_tma.cu: Test harness for TMA FMHA (HD=64 first) --- dsv4/kernels/attention/fmha_6warp_tma.cuh | 449 ++++++++++++++++++++++ dsv4/kernels/attention/fmha_tma.cuh | 239 ++++++++++++ tests/unit/test_fmha_tma.cu | 327 ++++++++++++++++ 3 files changed, 1015 insertions(+) create mode 100644 dsv4/kernels/attention/fmha_6warp_tma.cuh create mode 100644 dsv4/kernels/attention/fmha_tma.cuh create mode 100644 tests/unit/test_fmha_tma.cu diff --git a/dsv4/kernels/attention/fmha_6warp_tma.cuh b/dsv4/kernels/attention/fmha_6warp_tma.cuh new file mode 100644 index 00000000..2b298c36 --- /dev/null +++ b/dsv4/kernels/attention/fmha_6warp_tma.cuh @@ -0,0 +1,449 @@ +/** + * DSV4 FMHA — 6-warp specialized kernel, multi-row softmax, TMA async loads. + * + * ================================================================== + * DESIGN + * ================================================================== + * + * Same 6-warp design as fmha_6warp_multirow.cuh, but replaces scalar + * GMEM reads in the load warp with TMA async bulk copies. + * + * 6-warp CTA: warps 0-3 = softmax, warp 4 = MMA, warp 5 = TMA load. + * Grid: (1, n_h, batch) — each CTA processes one head of one batch item. + * + * TMA PIPELINE (single-stage, no overlap yet): + * 1. TMA warp issues cp.async.bulk.tensor.2d for Q, K tiles → SMEM (row-major) + * 2. mbarrier wait for TMA completion + * 3. Load warp transposes row-major SMEM → canonical K-major SMEM + * 4. MMA warp runs tcgen05.mma as before + * + * SMEM LAYOUT (same as non-TMA kernel, plus TMA staging buffers): + * - sQ_tma: (128, HD) row-major BF16 — TMA destination for Q + * - sK_tma: (128, 16) row-major BF16 — TMA destination for each K sub-tile + * - sQ: (128, HD) canonical K-major BF16 — MMA source for Q + * - sK: (128, 16) canonical K-major BF16 — MMA source for K + * - sPk: (128, 16) canonical K-major BF16 — P staging for PV + * - sV: (16, 16) canonical K-major BF16 — V staging for PV + * - sMbar: mbarrier for TMA completion + * - sTmemBase: TMEM base pointer + * - sRowMax, sRowSum: softmax intermediates + * + * NOTE: The row-major → canonical transpose is TEMPORARY. Once we + * validate TMA + SWIZZLE_128B, TMA will write directly in the swizzled + * canonical layout that MMA reads, eliminating the transpose entirely. + * But we do it the RIGHT way first: get TMA working, verify correctness, + * then optimize. + * ================================================================== + */ + +#pragma once + +#include "fmha_common.cuh" +#include "fmha_umma_desc.cuh" +#include "fmha_tma.cuh" + +namespace dsv4::kernels::attention { + +struct FmhaMultiRowTmaParams { + const bf16_t* __restrict__ q; + const bf16_t* __restrict__ k; + const bf16_t* __restrict__ v; + bf16_t* __restrict__ o; + float* __restrict__ lse; + int s_k, T; + float scale; + int head_dim; + int q_head_stride, q_batch_stride; + int k_head_stride, k_batch_stride; + int v_head_stride, v_batch_stride; + int o_head_stride, o_batch_stride; + int lse_head_stride, lse_batch_stride; + // TMA descriptors (device pointers to CUtensorMap in GMEM) + CUtensorMap* __restrict__ tma_q; // Q: (T, HD) + CUtensorMap* __restrict__ tma_k; // K: (s_k, HD) — used for per-sub-tile loads + CUtensorMap* __restrict__ tma_v; // V: (HD, s_k) — used for per-sub-tile loads +}; + +template +__global__ void __launch_bounds__(192) +fmha_6warp_tma_kernel(FmhaMultiRowTmaParams params) { + static constexpr int NKT_QK = HD / MMA_K_BF16; + static constexpr int NKT_PV = SK_TILE / MMA_K_BF16; + static constexpr int N_NSUB = HD / 16; + static constexpr int TILE_SZ = 128 * MMA_K_BF16; + static constexpr int V_SUB_SZ = 16 * MMA_K_BF16; + static constexpr int TMEM_N = (HD <= 128) ? 128 : 256; + static constexpr int MAX_ROWS = 128; + static constexpr int CORES_MN = 128 / 8; + static constexpr int NUM_READS = SK_TILE / 8; + + const int head_idx = blockIdx.y; + const int batch_idx = blockIdx.z; + const int tid = threadIdx.x; + const int wid = tid / 32; + const int lane = tid % 32; + const bool is_softmax_warp = (wid < 4); + const bool is_mma_warp = (wid == 4); + const bool is_load_warp = (wid == 5); + const int T = params.T; + const int s_k = params.s_k; + const float scale = params.scale; + + const bf16_t* __restrict__ q_head = params.q + head_idx * params.q_head_stride + batch_idx * params.q_batch_stride; + const bf16_t* __restrict__ k_head = params.k + head_idx * params.k_head_stride + batch_idx * params.k_batch_stride; + const bf16_t* __restrict__ v_head = params.v + head_idx * params.v_head_stride + batch_idx * params.v_batch_stride; + bf16_t* __restrict__ o_head = params.o + head_idx * params.o_head_stride + batch_idx * params.o_batch_stride; + float* __restrict__ lse_head = params.lse ? params.lse + head_idx * params.lse_head_stride + batch_idx * params.lse_batch_stride : nullptr; + + // TMA descriptor pointers (rebased per head/batch) + // These point to the base Q/K/V tensors. We offset coordinates for head/batch. + CUtensorMap* __restrict__ tma_q = params.tma_q; + CUtensorMap* __restrict__ tma_k = params.tma_k; + CUtensorMap* __restrict__ tma_v = params.tma_v; + + // ================================================================== + // SMEM allocation + // ================================================================== + // Layout: + // sTmemBase (4B) | sMbar (8B, 128B-aligned) | sRowMax (128×4B) | + // sRowSum (128×4B) | sQ_tma (128×HD, 128B-aligned, row-major) | + // sK_tma (128×16, 128B-aligned, row-major) | + // sQ (128×HD, 128B-aligned, canonical) | + // sK (128×16, 128B-aligned, canonical) | + // sPk (128×16, 128B-aligned, canonical) | + // sV_tma (16×128, 128B-aligned, row-major) | + // sV (16×16, 128B-aligned, canonical) + // ================================================================== + extern __shared__ char sbuf[]; + uint32_t* sTmemBase = (uint32_t*)sbuf; + size_t off = 4; // sTmemBase + + // sMbar: 128B-aligned + off = (off + 127) & ~(size_t)127; + uint64_t* sMbar = (uint64_t*)(sbuf + off); + off += 8; + + // sRowMax, sRowSum + float* sRowMax = (float*)(sbuf + off); off += MAX_ROWS * sizeof(float); + float* sRowSum = (float*)(sbuf + off); off += MAX_ROWS * sizeof(float); + + // sQ_tma: row-major (T rows, HD cols), padded to 128 rows for TMA tile + off = (off + 127) & ~(size_t)127; + bf16_t* sQ_tma = (bf16_t*)(sbuf + off); off += 128 * HD * sizeof(bf16_t); + + // sK_tma: row-major (128 rows, 16 cols) — one K sub-tile at a time + off = (off + 127) & ~(size_t)127; + bf16_t* sK_tma = (bf16_t*)(sbuf + off); off += 128 * MMA_K_BF16 * sizeof(bf16_t); + + // sQ: canonical K-major (128, HD) for MMA + off = (off + 127) & ~(size_t)127; + bf16_t* sQ = (bf16_t*)(sbuf + off); off += 128 * HD * sizeof(bf16_t); + + // sK: canonical K-major (128, 16) for MMA + off = (off + 127) & ~(size_t)127; + bf16_t* sK = (bf16_t*)(sbuf + off); off += 128 * MMA_K_BF16 * sizeof(bf16_t); + + // sPk: canonical K-major (128, 16) for P staging in PV + off = (off + 127) & ~(size_t)127; + bf16_t* sPk = (bf16_t*)(sbuf + off); off += 128 * MMA_K_BF16 * sizeof(bf16_t); + + // sV_tma: row-major (16 rows, 128 cols) — V sub-tile for PV + off = (off + 127) & ~(size_t)127; + bf16_t* sV_tma = (bf16_t*)(sbuf + off); off += 16 * 128 * sizeof(bf16_t); + + // sV: canonical K-major (16, 16) for MMA PV + off = (off + 127) & ~(size_t)127; + bf16_t* sV = (bf16_t*)(sbuf + off); off += V_SUB_SZ * sizeof(bf16_t); + + // ================================================================== + // Initialize mbarrier (one thread) + // ================================================================== + if (tid == 0) { + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_mbar_init(mbar_addr); + } + + // TMEM alloc + if (is_mma_warp) { + uint32_t smem_ptr = __cvta_generic_to_shared(sTmemBase); + tmem_alloc(smem_ptr, TMEM_N); + } + __syncthreads(); + uint32_t tb = *sTmemBase; + + // Row assignment for softmax warps + const bool my_warp_active = (T <= 32) ? (wid == 0) : is_softmax_warp; + const int my_row = my_warp_active ? (wid * 32 + lane) : 0; + const bool my_row_active = my_warp_active && (my_row < T); + + // ================================================================== + // TMA LOAD Q — full Q matrix (T, HD) + // ================================================================== + // Issue TMA load for Q. The TMA descriptor covers the full (T, HD) + // tensor for this head/batch. We load starting at (0, 0) into sQ_tma. + // ================================================================== + if (is_load_warp && lane == 0) { + uint32_t smem_dst = (uint32_t)__cvta_generic_to_shared(sQ_tma); + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_load_2d(smem_dst, (uint64_t)tma_q, mbar_addr, 0, 0); + } + + // Wait for Q TMA completion + if (is_load_warp && lane == 0) { + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_mbarrier_wait(mbar_addr); + } + __syncthreads(); + + // Transpose sQ_tma (row-major) → sQ (canonical K-major) + // Q is (T, HD). Only T rows have data; rows T..127 are zero (TMA pads). + // The transpose function handles the conversion. + if (is_load_warp) { + write_smem_canonical<128, HD>(sQ, sQ_tma); + } + + // ================================================================== + // QK GEMM → S in TMEM (loop over K sub-tiles) + // ================================================================== + for (int kt = 0; kt < NKT_QK; kt++) { + // --- TMA load K sub-tile --- + // K is (s_k, HD) in GMEM. We load a (s_k, 16) sub-tile starting + // at column kt*16. TMA coordinates: (coord_x = kt*16, coord_y = 0) + // After TMA, sK_tma contains (s_k, 16) in row-major. + // Then transpose to canonical sK for MMA. + + // Re-init mbarrier for this K-tile load + if (tid == 0) { + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_mbarrier_init(mbar_addr); + } + __syncthreads(); + + if (is_load_warp && lane == 0) { + uint32_t smem_dst = (uint32_t)__cvta_generic_to_shared(sK_tma); + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + // TMA load: K sub-tile at column offset kt*16, row offset 0 + tma_load_2d(smem_dst, (uint64_t)tma_k, mbar_addr, kt * MMA_K_BF16, 0); + } + + // Wait for K TMA completion + if (is_load_warp && lane == 0) { + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_mbarrier_wait(mbar_addr); + } + __syncthreads(); + + // Transpose sK_tma → sK (canonical) + if (is_load_warp) { + write_smem_canonical<128, MMA_K_BF16>(sK, sK_tma); + } + __syncthreads(); + + // MMA: sQ × sK → TMEM + if (is_mma_warp) { + uint32_t idesc = make_idesc(128, 128); + uint64_t dq = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sQ), 128); + uint64_t dk = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sK), 128); + if (tid == 128) umma_ss_f16(tb, dq, dk, idesc, kt > 0); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + } + __syncthreads(); + } + + // TMEM visibility fence + asm volatile("fence.sc.gpu;" ::: "memory"); + __syncthreads(); + + // ================================================================== + // SOFTMAX — compute P in registers (TWO passes over TMEM) + // (Identical to non-TMA multirow kernel) + // ================================================================== + + // Pass 1: row_max + float my_row_max = -INFINITY; + if (my_warp_active) { + 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 (my_row_active) { + for (int c = 0; c < 8; c++) { + int col = n * 8 + c; + if (col < s_k) my_row_max = fmaxf(my_row_max, tmp[c] * scale); + } + } + } + } + + if (my_row_active) sRowMax[my_row] = my_row_max; + __syncthreads(); + + // Pass 2: compute P values + float my_p_vals[SK_TILE]; + float my_row_sum = 0.0f; + + if (my_warp_active) { + float rm = my_row_active ? sRowMax[my_row] : 0.0f; + 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 (my_row_active) { + for (int c = 0; c < 8; c++) { + int col = n * 8 + c; + if (col < s_k) { + float p = expf(tmp[c] * scale - rm); + my_p_vals[col] = p; + my_row_sum += p; + } + } + } + } + } + + if (my_row_active) sRowSum[my_row] = my_row_sum; + __syncthreads(); + + // ================================================================== + // PV GEMM — write P to sPk per K-tile, accumulate O in TMEM + // ================================================================== + for (int n_sub = 0; n_sub < N_NSUB; n_sub++) { + int d_base = n_sub * 16; + for (int pv_kt = 0; pv_kt < NKT_PV; pv_kt++) { + const int col_start = pv_kt * MMA_K_BF16; + + // --- TMA load V sub-tile --- + // V is (HD, s_k) in GMEM. For PV, we need a (16, s_k) sub-tile + // starting at row d_base. But TMA loads tiles, not arbitrary slices. + // + // V sub-tile for PV: (16, MMA_K_BF16) = 16 rows × 16 cols + // In GMEM, V[d_base + dd, col_start + lr] = v_head[(d_base+dd)*s_k + col_start+lr] + // + // For TMA, the descriptor covers the full (HD, s_k) V tensor. + // We load a (16, 128) tile starting at (col_start, d_base). + // Wait — V in GMEM is (HD, s_k). A (16, 128) TMA tile at + // coord (col=col_start, row=d_base) loads V[d_base..d_base+15, col_start..col_start+127]. + // That's exactly what we need for sV. + // + // But our V MMA sub-tile is (128, 16) in canonical layout, + // which represents the (16, 128) V sub-tile transposed for the + // PV GEMM B operand. The TMA will load (16, 128) row-major → + // we need to transpose to canonical (128, 16). + + // Re-init mbarrier + if (tid == 0) { + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_mbarrier_init(mbar_addr); + } + __syncthreads(); + + // Zero sPk + if (is_load_warp) { + for (int i = lane; i < TILE_SZ; i += 32) sPk[i] = 0; + } + __syncthreads(); + + // Softmax warps: write P to sPk (same as non-TMA kernel) + if (my_row_active) { + for (int c = 0; c < MMA_K_BF16; c++) { + int gc = col_start + c; + int ck = c/8, lc = c%8; + int core_mn = my_row/8, local_r = my_row%8; + sPk[ck*CORES_MN*64 + core_mn*64 + local_r*8 + lc] = f32_to_bf16(my_p_vals[gc]); + } + } + __syncthreads(); + + // TMA load V sub-tile: (16, 128) at (col=col_start, row=d_base) + if (is_load_warp && lane == 0) { + uint32_t smem_dst = (uint32_t)__cvta_generic_to_shared(sV_tma); + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_load_2d(smem_dst, (uint64_t)tma_v, mbar_addr, col_start, d_base); + } + + if (is_load_warp && lane == 0) { + uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + tma_mbarrier_wait(mbar_addr); + } + __syncthreads(); + + // Transpose sV_tma (16, 128) row-major → sV (128, 16) canonical + // This is a TRANSPOSE: (16, 128) → (128, 16) + // In the canonical layout, the B operand for PV is (BLOCK_N=128, BLOCK_K=16). + // The row-major (16, 128) from TMA is V[d_base..d_base+15, col_start..col_start+127]. + // We need B[r, d] where r = sequence position, d = head dim offset. + // B[r, d] = V[d, r] = V_tma[d - d_base, r - col_start] for d in [d_base, d_base+16), r in [col_start, col_start+128). + // So B[r, d] = sV_tma[(d - d_base) * 128 + (r - col_start)] — row-major in (16, 128). + if (is_load_warp) { + constexpr int SV_CORES_MN = 128 / 8; // 16 + constexpr int SV_CORES_K = 16 / 8; // 2 + for (int i = lane; i < 128 * 16; i += 32) sV[i] = 0; + for (int i = lane; i < 16 * 128; i += 32) { + int d = i / 128; // row in V_tma = head dim offset + int r = i % 128; // col in V_tma = sequence position + // B[r, d] in canonical: core_mn = r/8, core_k = d/8, local_r = r%8, local_c = d%8 + int core_mn = r / 8; + int core_k = d / 8; + int local_r = r % 8; + int local_c = d % 8; + int dst_idx = core_k * SV_CORES_MN * 64 + core_mn * 64 + local_r * 8 + local_c; + sV[dst_idx] = sV_tma[i]; + } + } + __syncthreads(); + + // MMA: sPk × sV → TMEM + if (is_mma_warp) { + uint32_t idesc_pv = make_idesc(128, 16); + uint64_t dp = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sPk), 128); + uint64_t dv = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sV), 16); + if (tid == 128) umma_ss_f16(tb + n_sub*16, dp, dv, idesc_pv, pv_kt > 0); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + } + __syncthreads(); + } + } + + // Ensure PV output is visible + asm volatile("fence.sc.gpu;" ::: "memory"); + __syncthreads(); + + // ================================================================== + // EPILOGUE: TMEM → regs → normalize → BF16 → GMEM + LSE output + // (Identical to non-TMA multirow kernel) + // ================================================================== + if (my_warp_active) { + float rm = my_row_active ? sRowMax[my_row] : 0.0f; + float rs = my_row_active ? sRowSum[my_row] : 0.0f; + float inv_rs = my_row_active ? (1.0f / rs) : 0.0f; + + for (int n = 0; n < N_NSUB * 2; 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 (my_row_active) { + for (int c = 0; c < 8; c++) { + int d = n * 8 + c; + if (d < HD) o_head[my_row * HD + d] = f32_to_bf16(tmp[c] * inv_rs); + } + } + } + + if (my_row_active && lse_head) lse_head[my_row] = logf(rs) + rm; + } + __syncthreads(); + + if (is_mma_warp) tmem_dealloc(tb, TMEM_N); +} + +} // namespace dsv4::kernels::attention diff --git a/dsv4/kernels/attention/fmha_tma.cuh b/dsv4/kernels/attention/fmha_tma.cuh new file mode 100644 index 00000000..72af54ba --- /dev/null +++ b/dsv4/kernels/attention/fmha_tma.cuh @@ -0,0 +1,239 @@ +/** + * DSV4 FMHA — TMA async load infrastructure for Blackwell SM100. + * + * ================================================================== + * DESIGN + * ================================================================== + * + * Replaces scalar GMEM reads in the load warp with async TMA bulk + * copies via cp.async.bulk.tensor.2d. The pipeline: + * + * Host: CUtensorMap creation for Q, K, V tiles + * Kernel: + * 1. TMA warp issues cp.async.bulk.tensor.2d → SMEM (row-major) + * 2. mbarrier wait for TMA completion + * 3. Load warp transposes row-major SMEM → canonical K-major SMEM + * 4. MMA warp runs tcgen05.mma as before + * + * For double-buffered pipeline overlap (future): + * - Two SMEM buffers per tensor (sQ0/sQ1, sK0/sK1) + * - TMA load of K-tile (kt+1) overlaps with MMA on K-tile (kt) + * - Pipeline stages managed via mbarrier arrive/wait + * + * ================================================================== + * TMA DESCRIPTOR LAYOUT + * ================================================================== + * + * We create 2D CUtensorMap descriptors for each tile the kernel needs: + * + * Q tile: (T, HD) — one tile for the full Q + * K tile: (s_k, HD) — one tile for the full K (or (128, 16) per K-sub-tile) + * V tile: (HD, s_k) — transposed, one tile for the full V + * + * TMA copies data from GMEM to SMEM in row-major order. After TMA + * completion, the load warp transposes from row-major to the + * canonical K-major core-matrix layout that tcgen05.mma expects. + * + * For the multirow kernel, Q is (T, HD) and K is (s_k, HD). + * Since TMA operates on 2D tiles and our SMEM is (128, 16) per + * MMA K-tile, we have two choices: + * + * Option A: TMA load full (T, HD) → row-major SMEM → transpose + * - One TMA descriptor for Q, one for K + * - Larger SMEM footprint (need row-major + canonical) + * - Simpler descriptor management + * + * Option B: TMA load per (128, 16) K-sub-tile + * - One TMA descriptor, multiple TMA issues with different coords + * - Same SMEM as current (no double buffer needed for single-stage) + * - Matches the existing K-tiling loop structure + * + * We choose Option B: TMA per (128, 16) K-sub-tile. This: + * - Reuses the exact same SMEM layout as the current kernel + * - Fits the existing QK loop structure (kt = 0..NKT_QK-1) + * - Enables future pipeline overlap with minimal changes + * - The TMA descriptor covers the full (T, HD) or (s_k, HD) tensor, + * and we issue TMA loads for specific (col, row) coordinates + * targeting each 128×16 tile + * + * ================================================================== + * MBARRIER PROTOCOL + * ================================================================== + * + * TMA async copies use mbarrier for completion signaling: + * + * 1. Init mbarrier with expected transaction count = 1 + * 2. Issue cp.async.bulk.tensor.2d with the mbarrier + * 3. Wait on mbarrier parity (spin or yield) + * 4. After wait returns, SMEM data is ready + * + * The mbarrier lives in SMEM. One mbarrier per outstanding TMA + * operation. For single-stage (no overlap), we use one mbarrier + * and wait immediately after issue. + * + * ================================================================== + * SWIZZLE CONSIDERATIONS + * ================================================================== + * + * TMA descriptors support SWIZZLE_NONE, SWIZZLE_32B, SWIZZLE_64B, + * SWIZZLE_128B. The swizzle pattern in SMEM matches what UMMA + * descriptors expect when using make_umma_desc_kmajor_sw128. + * + * Current kernel uses SWIZZLE_NONE (make_umma_desc_kmajor_none). + * With TMA, we have two paths: + * + * Path 1: TMA with SWIZZLE_NONE → SMEM is row-major → transpose to canonical + * Path 2: TMA with SWIZZLE_128B → SMEM is swizzled → UMMA reads directly + * + * Path 2 is the production target: no transpose needed, TMA writes + * in the exact layout MMA reads. But getting the swizzle right is + * tricky and needs careful verification. + * + * We start with Path 1 (SWIZZLE_NONE + transpose) to get TMA working, + * then upgrade to Path 2 (SWIZZLE_128B, zero-copy) for performance. + * ================================================================== + */ + +#pragma once + +#include "fmha_common.cuh" +#include + +namespace dsv4::kernels::attention { + +// ================================================================== +// TMA descriptor helpers (host-side) +// ================================================================== +// These are called from host code to create CUtensorMap objects +// that the kernel uses for TMA async copies. +// ================================================================== + +/** + * Create a 2D TMA descriptor for a BF16 tensor of shape (rows, cols). + * The tensor is row-major in GMEM with stride = cols. + * TMA tile dimensions are (tile_rows, tile_cols). + * + * The descriptor is written to `out` (host memory). + * Must be copied to device memory before kernel launch. + */ +inline bool create_tma_desc_2d_bf16( + CUtensorMap* out, + const void* gmem_ptr, // device pointer to the BF16 tensor + uint64_t rows, // global dimension 0 (number of rows) + uint64_t cols, // global dimension 1 (number of columns) + uint32_t tile_rows, // TMA tile dimension 0 + uint32_t tile_cols, // TMA tile dimension 1 + CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_NONE +) { + // Global dimensions: (cols, rows) — TMA uses innermost-first ordering + uint64_t global_dim[] = {cols, rows}; + // Global strides: (1, cols) — element stride in each dimension + uint64_t global_str[] = {1, cols}; + // Tile dimensions: (tile_cols, tile_rows) — innermost-first + uint32_t tile_dim[] = {tile_cols, tile_rows}; + // Tile strides: (1, tile_cols) + uint32_t tile_str[] = {1, tile_cols}; + + CUresult res = cuTensorMapEncodeTiled( + out, + CU_TENSOR_MAP_DATA_TYPE_UINT16, // BF16 = 2 bytes = UINT16 + 2, // 2D tensor + const_cast(gmem_ptr), + global_dim, global_str, tile_dim, tile_str, + CU_TENSOR_MAP_INTERLEAVE_NONE, + swizzle, + CU_TENSOR_MAP_L2_PROMOTION_NONE, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE + ); + return res == CUDA_SUCCESS; +} + +// ================================================================== +// TMA kernel-side operations +// ================================================================== + +/** + * Initialize an mbarrier in SMEM with expected transaction count = 1. + * Only one thread should call this. + */ +__device__ __forceinline__ void tma_mbarrier_init(uint32_t smem_mbar) { + asm volatile("mbarrier.init.shared.b64 [%0], %1;" + :: "r"(smem_mbar), "r"(1)); +} + +/** + * Issue a 2D TMA async copy from GMEM to SMEM. + * + * The TMA descriptor must be in device memory (GMEM). + * Only ONE thread per CTA should issue the TMA copy. + * + * After issue, the data will be written to SMEM asynchronously. + * Use tma_mbarrier_wait to wait for completion. + * + * @param smem_dst SMEM destination address (via __cvta_generic_to_shared) + * @param tma_desc Pointer to CUtensorMap in device memory (uint64_t cast) + * @param smem_mbar SMEM mbarrier address (via __cvta_generic_to_shared) + * @param coord_x Column coordinate (innermost dimension) + * @param coord_y Row coordinate (outermost dimension) + */ +__device__ __forceinline__ void tma_load_2d( + uint32_t smem_dst, + uint64_t tma_desc, + uint32_t smem_mbar, + int coord_x, + int coord_y +) { + asm volatile( + "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes " + "[%0], [%1, {%3, %4}], [%2];" + :: "r"(smem_dst), + "l"(tma_desc), + "r"(smem_mbar), + "r"(coord_x), + "r"(coord_y) + : "memory" + ); +} + +/** + * Wait for mbarrier completion (spin-wait). + * Only ONE thread should wait (or all threads, but typically just the + * thread that issued the TMA copy). + * + * @param smem_mbar SMEM mbarrier address (via __cvta_generic_to_shared) + */ +__device__ __forceinline__ void tma_mbarrier_wait(uint32_t smem_mbar) { + int phase = 0; + asm volatile( + "{\n\t" + ".reg .pred p;\n\t" + "LOOP:\n\t" + "mbarrier.try_wait.parity.shared.b64 p, [%0], %1;\n\t" + "@p bra DONE;\n\t" + "bra LOOP;\n\t" + "DONE:\n\t" + "}" + :: "r"(smem_mbar), "r"(phase) + : "memory" + ); +} + +/** + * Invalidate L2 prefetch to ensure TMA sees fresh data. + * Call before issuing TMA loads if the data was recently written. + */ +__device__ __forceinline__ void tma_cp_commit() { + asm volatile("cp.async.commit_group;" ::: "memory"); +} + +// ================================================================== +// TMA parameter structure +// ================================================================== + +struct FmhaTmaDescriptors { + CUtensorMap* __restrict__ tma_q; // Q descriptor: (T, HD) row-major + CUtensorMap* __restrict__ tma_k; // K descriptor: (s_k, HD) row-major + CUtensorMap* __restrict__ tma_v; // V descriptor: (HD, s_k) row-major +}; + +} // namespace dsv4::kernels::attention diff --git a/tests/unit/test_fmha_tma.cu b/tests/unit/test_fmha_tma.cu new file mode 100644 index 00000000..7eb49fee --- /dev/null +++ b/tests/unit/test_fmha_tma.cu @@ -0,0 +1,327 @@ +/** + * Test TMA async FMHA kernel (6-warp, multi-row, TMA loads). + * Compile with -DHD_VAL=64 etc. + * + * Tests: + * 1. TMA load correctness (Q, K, V tiles match reference) + * 2. Full FMHA with TMA loads, T=1..128 + * 3. Multi-head and batched launches + * 4. Regression check against non-TMA kernel output + */ + +#include +#include +#include +#include +#include +#include + +#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" + +// ================================================================== +// SMEM computation +// ================================================================== +static int compute_smem_tma() { + size_t off = 0; + off += 4; // sTmemBase + off = (off + 127) & ~(size_t)127; + off += 8; // sMbar + off += MAX_T * sizeof(float); // sRowMax + off += MAX_T * sizeof(float); // sRowSum + off = (off + 127) & ~(size_t)127; + off += 128 * HD * sizeof(bf16_t); // sQ_tma + off = (off + 127) & ~(size_t)127; + off += 128 * MMA_K_BF16 * sizeof(bf16_t); // sK_tma + off = (off + 127) & ~(size_t)127; + off += 128 * HD * sizeof(bf16_t); // sQ + off = (off + 127) & ~(size_t)127; + off += 128 * MMA_K_BF16 * sizeof(bf16_t); // sK + off = (off + 127) & ~(size_t)127; + off += 128 * MMA_K_BF16 * sizeof(bf16_t); // sPk + off = (off + 127) & ~(size_t)127; + off += 16 * 128 * sizeof(bf16_t); // sV_tma + off = (off + 127) & ~(size_t)127; + off += 16 * MMA_K_BF16 * sizeof(bf16_t); // sV + return (int)off; +} + +// ================================================================== +// Reference attention +// ================================================================== +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; + } +} + +// ================================================================== +// TMA descriptor creation for a head/batch slice of Q, K, V +// ================================================================== +// The challenge: TMA descriptors must point to contiguous GMEM regions. +// Q for head h, batch b is at q + h*q_head_stride + b*q_batch_stride. +// The shape is (T, HD) with stride (HD, 1). +// +// We create one TMA descriptor per head, per batch (or per head for batch=1). +// For simplicity in the test, we create descriptors for each test case. +// ================================================================== + +struct TmaDescSet { + CUtensorMap tma_q; + CUtensorMap tma_k; + CUtensorMap tma_v; + CUtensorMap* d_tma_q; + CUtensorMap* d_tma_k; + CUtensorMap* d_tma_v; + + bool create(bf16_t* d_q, bf16_t* d_k, bf16_t* d_v, + int T, int hd, int s_k, + int q_stride, int k_stride, int v_stride) { + // Q: (T, HD) row-major, stride = HD + // TMA tile: we need tiles of (128, 16) for the Q sub-tiles used in MMA. + // But Q is (T, HD) and we want to load the FULL Q at once for the first + // iteration, then use sQ across all K sub-tiles. + // TMA tile size must be ≤ the global dimensions. + // For Q: (T, HD). TMA tile = (min(T, 128), HD) won't work for TMA — + // tile must be a sub-tile, not the full tensor. + // + // Actually: TMA can load the full tensor if the tile matches the tensor. + // For (T, HD) with T ≤ 128 and HD ≤ 256, a tile of (128, HD) works + // if we set tile_dims = (HD, 128). + // + // But TMA requires tile dimensions to be power-of-2 aligned in certain ways. + // The safest approach: use the (128, 16) tile for ALL sub-tiles, even Q. + // For Q, we issue NKT_QK TMA loads, one per K sub-tile, loading + // Q columns [kt*16, kt*16+16). + // + // Wait — that changes the kernel design. Currently we load Q once and + // reuse across all K sub-tiles. If we TMA-load Q per K-sub-tile, we + // waste bandwidth re-reading Q NKT_QK times. + // + // The right approach: TMA load the full Q with a (T, HD) tile. + // TMA tile dimensions can be (HD, T) if HD and T are valid TMA tile sizes. + // TMA tile size requirements: each dimension must be 1, 2, 4, 8, 16, 32, 64, 128, or 256 + // (power of 2 up to 256), AND the tile must be ≤ the global dimension. + // + // For HD=64: tile_cols=64, tile_rows=T. But T can be 1..128. + // tile_rows must be power of 2. So we pad Q to (128, 64) and use tile (64, 128). + // + // This works! Q is (T, HD) with T ≤ 128, HD ≤ 256. We pad to (128, HD) + // in GMEM (or just let TMA read the extra rows — they'll be garbage but + // the kernel zeros them via the canonical layout). + // + // For K: (s_k, HD). We want to load (s_k, 16) sub-tiles. + // TMA tile = (16, s_k). Load each sub-tile with coord (kt*16, 0). + // + // For V: (HD, s_k). We want to load (16, s_k) sub-tiles. + // TMA tile = (s_k, 16). Load with coord (0, d_base). + // + // Let's create the descriptors. + + // Q: (128, HD) — padded to 128 rows. TMA tile = (HD, 128). + // The data in GMEM starts at d_q, shape (T, HD), stride (HD, 1). + // We treat it as (128, HD) — rows beyond T are garbage, kernel ignores them. + uint32_t q_tile_rows = 128; + if (!create_tma_desc_2d_bf16(&tma_q, d_q, 128, (uint64_t)hd, q_tile_rows, (uint32_t)hd)) { + printf(" Failed to create Q TMA desc\n"); return false; + } + + // K: (s_k, HD) — TMA tile = (16, s_k) to load one K sub-tile at a time + if (!create_tma_desc_2d_bf16(&tma_k, d_k, (uint64_t)s_k, (uint64_t)hd, (uint32_t)s_k, 16)) { + printf(" Failed to create K TMA desc\n"); return false; + } + + // V: (HD, s_k) — TMA tile = (s_k, 16) to load (16, s_k) sub-tiles + if (!create_tma_desc_2d_bf16(&tma_v, d_v, (uint64_t)hd, (uint64_t)s_k, (uint32_t)s_k, 16)) { + printf(" Failed to create V TMA desc\n"); return false; + } + + // Copy to device + cudaMalloc(&d_tma_q, sizeof(CUtensorMap)); + cudaMalloc(&d_tma_k, sizeof(CUtensorMap)); + cudaMalloc(&d_tma_v, sizeof(CUtensorMap)); + cudaMemcpy(d_tma_q, &tma_q, sizeof(CUtensorMap), cudaMemcpyHostToDevice); + 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_q) { cudaFree(d_tma_q); d_tma_q = nullptr; } + if (d_tma_k) { cudaFree(d_tma_k); d_tma_k = nullptr; } + if (d_tma_v) { cudaFree(d_tma_v); d_tma_v = nullptr; } + } +}; + +// ================================================================== +// Test single KV tile +// ================================================================== +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; + + bf16_t* h_q = (bf16_t*)malloc(total_heads * T * 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 * T * HD, sizeof(bf16_t)); + float* h_lse = (float*)calloc(total_heads * 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 * T * 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 * T * HD * sizeof(bf16_t)); + cudaMalloc(&d_lse, total_heads * T * sizeof(float)); + cudaMemcpy(d_q, h_q, total_heads * T * 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 ok = 1; + int failed = 0; + float min_cos = 1.0f; + + // Test each head separately (per-head TMA descriptors) + for (int b = 0; b < batch; b++) { + for (int h = 0; h < n_h; h++) { + int idx = b * n_h + h; + + // Create TMA descriptors for this head + TmaDescSet tma; + bf16_t* d_q_h = d_q + idx * T * 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_q_h, d_k_h, d_v_h, T, HD, SK, HD, HD, SK)) { + printf(" TMA desc creation failed for head %d batch %d\n", h, b); + ok = 0; continue; + } + + FmhaMultiRowTmaParams params; + params.q = d_q_h; params.k = d_k_h; params.v = d_v_h; + params.o = d_o + idx * T * HD; params.lse = d_lse + idx * T; + params.s_k = SK; params.T = T; params.scale = SCALE; params.head_dim = HD; + params.q_head_stride = T * HD; params.q_batch_stride = n_h * T * 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 = T * HD; params.o_batch_stride = n_h * T * HD; + params.lse_head_stride = T; params.lse_batch_stride = n_h * T; + params.tma_q = tma.d_tma_q; + params.tma_k = tma.d_tma_k; + params.tma_v = tma.d_tma_v; + + int smem = compute_smem_tma(); + if (smem > 48 * 1024) + cudaFuncSetAttribute(fmha_6warp_tma_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem); + + dim3 grid(1, 1, 1); // one head at a time + fmha_6warp_tma_kernel<<>>(params); + + cudaError_t err = cudaDeviceSynchronize(); + if (err != cudaSuccess) { + printf(" CUDA ERROR b=%d h=%d: %s\n", b, h, cudaGetErrorString(err)); + ok = 0; tma.destroy(); continue; + } + + // Verify + bf16_t* h_o_head = (bf16_t*)malloc(T * HD * sizeof(bf16_t)); + float* h_lse_head = (float*)malloc(T * sizeof(float)); + cudaMemcpy(h_o_head, d_o + idx * T * HD, T * HD * sizeof(bf16_t), cudaMemcpyDeviceToHost); + cudaMemcpy(h_lse_head, d_lse + idx * T, T * sizeof(float), cudaMemcpyDeviceToHost); + + float o_ref[MAX_T * 512]; float lse_ref[MAX_T]; + reference_attention_multirow( + h_q + idx*T*HD, h_k + idx*SK*HD, h_v + idx*HD*SK, + o_ref, lse_ref, HD, T, SK, SCALE); + + for (int t = 0; t < T; t++) { + float cs=0,na=0,nb=0; + for (int d=0;d1e-4f){cs+=a*b2;na+=a*a;nb+=b2*b2;} + } + cs /= (sqrtf(na)*sqrtf(nb)+1e-10f); + if(cs 0.01f) { printf(" FAIL LSE b=%d h=%d t=%d kernel=%.6f ref=%.6f err=%.6f\n",b,h,t,h_lse_head[t],lse_ref[t],lse_err); failed++; } + } + + free(h_o_head); free(h_lse_head); + tma.destroy(); + } + } + + printf(" min_cos=%.8f %s\n", min_cos, failed==0?"PASSED":"FAILED"); + if (failed > 0) ok = 0; + + 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 ok; +} + +int main() { + printf("TMA Async FMHA test (HD=%d)\n", HD); + + int ok = 1; + + // 1. Single KV tile tests + printf("\n--- Single KV tile tests (TMA) ---\n"); + ok &= test_single(1); + ok &= test_single(2); + ok &= test_single(4); + ok &= test_single(8); + ok &= test_single(16); + ok &= test_single(32); + ok &= test_single(64); + ok &= test_single(128); + + // 2. Multi-head + printf("\n--- Multi-head tests (TMA) ---\n"); + ok &= test_single(4, 4, 1); + ok &= test_single(16, 4, 1); + + printf("\n%s\n", ok ? "ALL PASSED" : "SOME FAILED"); + return ok ? 0 : 1; +}