diff --git a/dsv4/kernels/attention/fmha_6warp_tma_multitile.cuh b/dsv4/kernels/attention/fmha_6warp_tma_multitile.cuh new file mode 100644 index 00000000..a8555f2b --- /dev/null +++ b/dsv4/kernels/attention/fmha_6warp_tma_multitile.cuh @@ -0,0 +1,301 @@ +/** + * DSV4 FMHA — 6-warp TMA kernel, multi-tile KV, T=1 decode. + * + * Register-resident O accumulator for in-kernel multi-tile KV merge. + * Avoids the D1.5 TMEM round-trip problem. + * + * ONLY supports T=1 decode. For T>1, use fmha_6warp_tma_multirow + * with Python KV merge. + * + * ================================================================== + * MULTI-TILE KV DESIGN + * ================================================================== + * + * Outer loop: kv_tile = 0..n_kv_tiles-1 + * Inner loop: kt = 0..NKT_QK-1 (K sub-tiles within a KV tile) + * + * For each KV tile: + * 1. TMA load K sub-tile → sTmaBuf → canonical sK + * 2. QK MMA → S in TMEM + * 3. Softmax (with online rescale of running O) + * 4. PV MMA → O_tile in TMEM + * 5. Read O_tile from TMEM → registers + * 6. Rescale running O: o_acc *= exp(running_max - tile_max) + * 7. Add O_tile to o_acc + * 8. Update running_max, running_sum + * + * Final: o_acc /= running_sum → BF16 → GMEM + LSE + * + * Register pressure (T=1): o_acc[HD] = 256-1024 bytes per thread. + * Only lane 0 of warp 0 holds the accumulator. + */ + +#pragma once + +#include "fmha_common.cuh" +#include "fmha_umma_desc.cuh" +#include "fmha_tma.cuh" + +namespace dsv4::kernels::attention { + +struct FmhaTmaMultiTileParams { + const bf16_t* __restrict__ q; + CUtensorMap* __restrict__ tma_k; // Array of [n_h] TMA descriptors for K: (s_k, HD) tile (128,16) + const bf16_t* __restrict__ v; // (HD, s_k) + bf16_t* __restrict__ o; + float* __restrict__ lse; + int s_k, n_h; + float scale; + int q_head_stride, q_batch_stride; + int v_head_stride, v_batch_stride; + int o_head_stride, o_batch_stride; + int lse_head_stride, lse_batch_stride; +}; + +template +__global__ void __launch_bounds__(192) +fmha_6warp_tma_multitile_kernel(FmhaTmaMultiTileParams 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 CORES_MN = 128 / 8; + static constexpr int NUM_READS = SK_TILE / 8; + static constexpr int TMA_TILE_BYTES = TILE_SZ * sizeof(bf16_t); + + 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_mma_warp = (wid == 4); + const bool is_load_warp = (wid == 5); + const int s_k = params.s_k; + const int n_kv_tiles = (s_k + SK_TILE - 1) / SK_TILE; + 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__ 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; + CUtensorMap* __restrict__ my_tma_k = params.tma_k + batch_idx * params.n_h + head_idx; + + // ================================================================ + // SMEM allocation + // ================================================================ + 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; + uint64_t* sMbar = (uint64_t*)(sbuf + off); off += 16; + off = (off + 127) & ~(size_t)127; + bf16_t* sTmaBuf = (bf16_t*)(sbuf + off); off += TILE_SZ * sizeof(bf16_t); + off = (off + 127) & ~(size_t)127; + bf16_t* sQ0 = (bf16_t*)(sbuf + off); off += TILE_SZ * sizeof(bf16_t); + off = (off + 127) & ~(size_t)127; + bf16_t* sK0 = (bf16_t*)(sbuf + off); off += TILE_SZ * sizeof(bf16_t); + off = (off + 127) & ~(size_t)127; + bf16_t* sPk = (bf16_t*)(sbuf + off); off += TILE_SZ * sizeof(bf16_t); + off = (off + 127) & ~(size_t)127; + bf16_t* sV = (bf16_t*)(sbuf + off); off += V_SUB_SZ * sizeof(bf16_t); + float* s_p_vals = (float*)(sbuf + off); off += SK_TILE * sizeof(float); + float* sTileMax = (float*)(sbuf + off); off += sizeof(float); + float* sTileSum = (float*)(sbuf + off); off += sizeof(float); + + // Init + if (is_mma_warp) 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; + const uint32_t mbar_addr = (uint32_t)__cvta_generic_to_shared(sMbar); + int phase = 0; + + // Load Q once (T=1) + if (is_load_warp) { + for (int i = lane; i < TILE_SZ; i += 32) sQ0[i] = 0; + for (int d = lane; d < HD; d += 32) { + int ck = d / 8, lc = d % 8; + sQ0[ck * CORES_MN * 64 + lc] = q_head[d]; + } + } + __syncthreads(); + + // Register accumulator + float o_acc[HD]; + float running_max = -INFINITY; + float running_sum = 0.0f; + if (wid == 0 && lane == 0) { + for (int d = 0; d < HD; d++) o_acc[d] = 0.0f; + } + + // ================================================================ + // Multi-tile KV loop + // ================================================================ + for (int kv_tile = 0; kv_tile < n_kv_tiles; kv_tile++) { + int kv_start = kv_tile * SK_TILE; + int kv_len = min(SK_TILE, s_k - kv_start); + + // ---- QK GEMM ---- + for (int kt = 0; kt < NKT_QK; kt++) { + // TMA load K sub-tile at (kt*16, kv_start) + if (is_load_warp && lane == 0) { + tma_load_2d((uint32_t)__cvta_generic_to_shared(sTmaBuf), (uint64_t)my_tma_k, + mbar_addr, kt * MMA_K_BF16, kv_start); + tma_mbarrier_arrive_expect_tx(mbar_addr, TMA_TILE_BYTES); + } + tma_mbarrier_wait(mbar_addr, phase); phase ^= 1; + __syncthreads(); + + // Convert sTmaBuf → canonical sK0 + for (int i = tid; i < TILE_SZ; i += 192) sK0[i] = 0; + for (int i = tid; i < kv_len * MMA_K_BF16; i += 192) { + int r = i / MMA_K_BF16, c = i % MMA_K_BF16; + int ck = c/8, lc = c%8, tmn = r/8, lr = r%8; + sK0[ck*CORES_MN*64 + tmn*64 + lr*8 + lc] = sTmaBuf[i]; + } + __syncthreads(); + + // MMA + if (is_mma_warp) { + uint32_t idesc = make_idesc(128, 128); + uint64_t dq = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sQ0), 128); + uint64_t dk = make_umma_desc_kmajor_none(__cvta_generic_to_shared(sK0), 128); + if (tid == 128) umma_ss_f16(tb, dq, dk, idesc, kt > 0); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + } + __syncthreads(); + } + asm volatile("fence.sc.gpu;" ::: "memory"); + __syncthreads(); + + // ---- Softmax (warp 0, lane 0, T=1) ---- + if (wid == 0) { + float s_vals[SK_TILE], row_max = -INFINITY; + 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 < kv_len) { + s_vals[col] = tmp[c] * scale; + row_max = fmaxf(row_max, tmp[c] * scale); + } + } + } + row_max = wmax(row_max); + float row_sum = 0.0f; + if (lane == 0) { + for (int j=0;j 0); + asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); + } + __syncthreads(); + } + } + asm volatile("fence.sc.gpu;" ::: "memory"); + __syncthreads(); + + // ---- Read O_tile from TMEM, rescale, accumulate ---- + if (wid == 0) { + float tile_max = *sTileMax; + float tile_sum = *sTileSum; + float o_tile[HD]; + + // Read O_tile from TMEM (warp-collective, but only lane 0 uses data) + 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 (lane == 0) for (int c=0;c<8;c++) { + int d = n*8+c; + if (d < HD) o_tile[d] = tmp[c]; + } + } + + // Online softmax rescale + accumulate + if (lane == 0) { + if (kv_tile == 0) { + running_max = tile_max; + running_sum = tile_sum; + for (int d = 0; d < HD; d++) o_acc[d] = o_tile[d]; + } else { + float old_max = running_max; + running_max = fmaxf(running_max, tile_max); + float rescale = expf(old_max - running_max); + for (int d = 0; d < HD; d++) o_acc[d] = o_acc[d] * rescale + o_tile[d] * expf(tile_max - running_max); + running_sum = running_sum * rescale + tile_sum * expf(tile_max - running_max); + } + } + } + __syncthreads(); + } + + // ================================================================ + // Final epilogue + // ================================================================ + if (wid == 0 && lane == 0) { + float inv_rs = 1.0f / running_sum; + for (int d = 0; d < HD; d++) o_head[d] = f32_to_bf16(o_acc[d] * inv_rs); + if (lse_head) lse_head[0] = logf(running_sum) + running_max; + } + __syncthreads(); + if (is_mma_warp) tmem_dealloc(tb, TMEM_N); +} + +} // namespace diff --git a/tests/unit/test_fmha_6warp_tma_multitile.cu b/tests/unit/test_fmha_6warp_tma_multitile.cu new file mode 100644 index 00000000..e3494c1f --- /dev/null +++ b/tests/unit/test_fmha_6warp_tma_multitile.cu @@ -0,0 +1,153 @@ +/** + * Test 6-warp TMA FMHA multi-tile KV kernel (s_k > 128). + * Tests in-kernel online softmax rescale across KV tiles. + */ + +#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 MY_MMA_K = 16; +constexpr int TILE_SZ = 128 * MY_MMA_K; + +#include "dsv4/kernels/attention/fmha_6warp_tma_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 += SK * 4; // s_p_vals + off += 4; // sTileMax + off += 4; // sTileSum + 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 s_k, float scale +) { + float s[4096]; + 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[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[d] = ov; + } + if (lse_ref) *lse_ref = logf(sm) + mx; +} + +int main() { + printf("=== 6-warp TMA FMHA multi-tile HD=%d ===\n", HD); + const float SCALE = 1.0f / sqrtf((float)HD); + + int total_fail = 0; + + for (int s_k : {128, 256, 384, 512}) { + printf("\n--- s_k=%d (%d KV tiles) ---\n", s_k, (s_k + 127) / 128); + + bf16_t* h_q = (bf16_t*)calloc(HD, sizeof(bf16_t)); + bf16_t* h_k = (bf16_t*)calloc(s_k * HD, sizeof(bf16_t)); + bf16_t* h_v = (bf16_t*)calloc(HD * s_k, sizeof(bf16_t)); + bf16_t* h_o = (bf16_t*)calloc(HD, sizeof(bf16_t)); + float* h_lse = (float*)calloc(1, sizeof(float)); + + srand(42); + for (int i=0;i 48*1024) + cudaFuncSetAttribute(fmha_6warp_tma_multitile_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem); + + fmha_6warp_tma_multitile_kernel<<<1, 192, smem>>>(params); + + cudaError_t err = cudaDeviceSynchronize(); + if (err != cudaSuccess) { + printf(" CUDA ERROR: %s\n", cudaGetErrorString(err)); + total_fail++; continue; + } + + cudaMemcpy(h_o, d_o, HD*sizeof(bf16_t), cudaMemcpyDeviceToHost); + + float* o_ref = (float*)calloc(HD, sizeof(float)); + reference_attention(h_q, h_k, h_v, o_ref, nullptr, HD, s_k, SCALE); + + float cs=0,na=0,nb=0; + for (int d=0;d 1e-4f) { cs+=a*b; na+=a*a; nb+=b*b; } + } + cs /= (sqrtf(na)*sqrtf(nb)+1e-10f); + printf(" cosine=%.8f %s\n", cs, cs>0.999f?"PASS":"FAIL"); + if (cs < 0.999f) total_fail++; + + if (HD <= 64 && total_fail == 0) { + printf(" O[0..3]: "); for(int d=0;d<4;d++) printf("%.6f ", bf16_to_f32_host(h_o[d])); printf("\n"); + printf(" ref[0..3]: "); for(int d=0;d<4;d++) printf("%.6f ", o_ref[d]); printf("\n"); + } + + cudaFree(d_q); cudaFree(d_k); cudaFree(d_v); cudaFree(d_o); cudaFree(d_lse); cudaFree(d_tma_k); + free(h_q); free(h_k); free(h_v); free(h_o); free(h_lse); free(o_ref); + } + + printf("\nOverall: %s\n", total_fail==0?"ALL PASSED":"SOME FAILED"); + return total_fail == 0 ? 0 : 1; +}