diff --git a/tests/unit/test_d1_multi_kv.py b/tests/unit/test_d1_multi_kv.py new file mode 100644 index 00000000..2d9e78fb --- /dev/null +++ b/tests/unit/test_d1_multi_kv.py @@ -0,0 +1,122 @@ +""" +FMHA D1: Test O rescale with multiple KV tiles (s_k > 128). + +DSV4 Pro uses top_k=1024 → s_k=1024 → n_kv_tiles=8. +The O rescale code (kt>0) is guarded with const_expr(n_kv_tiles > 1) +and uses hand-constructed TMEM atoms. Untested and likely broken. + +This test verifies O rescale correctness at s_k=256 (2 KV tiles). +""" +import torch, math +import cutlass.cute as cute +import cutlass.torch as ct +import cuda.bindings.driver as cuda +from dsv4.kernels.attention.fmha import FmhaKernel + + +def test_multi_kv(hd=64, s_k=256): + m = 128 + n_kv_tiles = s_k // 128 + torch.manual_seed(42) + + q = torch.randn(m, hd, 1, dtype=torch.bfloat16, device='cuda') + k = torch.randn(s_k, hd, 1, dtype=torch.bfloat16, device='cuda') + v = torch.randn(s_k, hd, dtype=torch.bfloat16, device='cuda') + c = torch.zeros(m, hd, 1, dtype=torch.bfloat16, device='cuda') + + # FP32 reference + qf = q[:, :, 0].float() + kf = k[:, :, 0].float() + scale = 1.0 / math.sqrt(hd) + attn_max = (qf @ kf.T * scale).max(dim=-1, keepdim=True)[0] + attn_exp = torch.exp(qf @ kf.T * scale - attn_max) + attn_sum = attn_exp.sum(dim=-1, keepdim=True) + ref_unnorm = attn_exp @ v.float() + ref_norm = (attn_exp / attn_sum) @ v.float() + ref_lse = (torch.log(attn_sum.squeeze(-1)) + attn_max.squeeze(-1))[0].item() + + lse_tensor = torch.zeros(m, 1, 1, dtype=torch.float32, device='cuda') + + kernel = FmhaKernel(head_dim=hd, s_k=s_k, use_smem_p=False, normalize=False) + pv_n_tile = kernel.pv_n_tile + n_pv_tiles = kernel.n_pv_tiles + + stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) + + # Compile with first PV tile + v_tile = v[:, 0:pv_n_tile].contiguous() + v_kernel = v_tile.unsqueeze(-1) + c_tile = torch.zeros(m, pv_n_tile, 1, dtype=torch.bfloat16, device='cuda') + + mQ = ct.from_dlpack(q).mark_layout_dynamic(leading_dim=ct.get_leading_dim(q)) + mK = ct.from_dlpack(k).mark_layout_dynamic(leading_dim=ct.get_leading_dim(k)) + mV = ct.from_dlpack(v_kernel).mark_layout_dynamic(leading_dim=ct.get_leading_dim(v_kernel)) + mC = ct.from_dlpack(c_tile).mark_layout_dynamic(leading_dim=ct.get_leading_dim(c_tile)) + mLSE = ct.from_dlpack(lse_tensor).mark_layout_dynamic(leading_dim=ct.get_leading_dim(lse_tensor)) + + print(f'hd={hd}, s_k={s_k} (n_kv_tiles={n_kv_tiles}, pv_n_tile={pv_n_tile}): Compiling...', flush=True) + compiled = cute.compile(kernel, mQ, mK, mV, mC, stream, mLSE) + + lse_val = None + for nt in range(n_pv_tiles): + v_start = nt * pv_n_tile + v_end = v_start + pv_n_tile + v_tile = v[:, v_start:v_end].contiguous() + v_kernel = v_tile.unsqueeze(-1) + c_tile = torch.zeros(m, pv_n_tile, 1, dtype=torch.bfloat16, device='cuda') + lse_tensor.zero_() + + mQ = ct.from_dlpack(q).mark_layout_dynamic(leading_dim=ct.get_leading_dim(q)) + mK = ct.from_dlpack(k).mark_layout_dynamic(leading_dim=ct.get_leading_dim(k)) + mV = ct.from_dlpack(v_kernel).mark_layout_dynamic(leading_dim=ct.get_leading_dim(v_kernel)) + mC = ct.from_dlpack(c_tile).mark_layout_dynamic(leading_dim=ct.get_leading_dim(c_tile)) + mLSE = ct.from_dlpack(lse_tensor).mark_layout_dynamic(leading_dim=ct.get_leading_dim(lse_tensor)) + + compiled(mQ, mK, mV, mC, stream, mLSE) + torch.cuda.synchronize() + + c[:, v_start:v_end, :] = c_tile + if nt == 0: + lse_val = lse_tensor[0, 0, 0].item() + + out_unnorm = c[:, :, 0].float() + out_norm = out_unnorm / attn_sum + cos_unnorm = torch.nn.functional.cosine_similarity( + out_unnorm.flatten().unsqueeze(0), ref_unnorm.flatten().unsqueeze(0) + ).item() + cos_norm = torch.nn.functional.cosine_similarity( + out_norm.flatten().unsqueeze(0), ref_norm.flatten().unsqueeze(0) + ).item() + lse_err = abs(lse_val - ref_lse) if lse_val is not None else float('inf') + + status = "PASS" if cos_unnorm >= 0.99 else "FAIL" + print(f'hd={hd}, s_k={s_k}: cos_unnorm {cos_unnorm:.6f} cos_norm {cos_norm:.6f} lse_err {lse_err:.6f} {status}') + return cos_unnorm, cos_norm, lse_err + + +def test(): + print("=== D1: Multi-KV-Tile O Rescale Test ===\n") + + # First: s_k=128 baseline (1 KV tile, no rescale needed) + print("--- Baseline: s_k=128 (1 KV tile) ---") + test_multi_kv(64, 128) + + # Critical test: s_k=256 (2 KV tiles, O rescale exercised) + print("\n--- s_k=256 (2 KV tiles, O rescale needed) ---") + test_multi_kv(64, 256) + + # s_k=384 (3 KV tiles) + print("\n--- s_k=384 (3 KV tiles) ---") + test_multi_kv(64, 384) + + # s_k=512 (4 KV tiles — Flash decode config) + print("\n--- s_k=512 (4 KV tiles, Flash decode) ---") + test_multi_kv(64, 512) + + # hd=128 with multi-KV + print("\n--- hd=128, s_k=256 ---") + test_multi_kv(128, 256) + + +if __name__ == '__main__': + test()