""" D2: Multi-CTA grid test. Tests the multi-CTA FMHA kernel with Q shape (n_h, T, hd, 1). Each CTA (indexed by block_idx_y) handles one query head. K/V are shared (MQA) — all CTAs load the same K/V. """ 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_cta(hd=64, n_h=2, s_k=128): T = 128 torch.manual_seed(42) # Q: (n_h, T, hd, 1) — head dimension outermost q = torch.randn(n_h, T, hd, 1, dtype=torch.bfloat16, device='cuda') # K/V: (s_k, hd, 1) — shared KV (no head dim) k = torch.randn(s_k, hd, 1, dtype=torch.bfloat16, device='cuda') v = torch.randn(s_k, hd, dtype=torch.bfloat16, device='cuda') # O: (n_h, T, hd, 1) o = torch.zeros(n_h, T, hd, 1, dtype=torch.bfloat16, device='cuda') # FP32 reference (un-normalized) qf = q[:, :, :, 0].float() # (n_h, T, hd) kf = k[:, :, 0].float() # (s_k, hd) vf = v.float() # (s_k, hd) scale = 1.0 / math.sqrt(hd) ref_unnorm = torch.zeros(n_h, T, hd, dtype=torch.float32, device='cuda') for h in range(n_h): attn = qf[h] @ kf.T * scale attn_max = attn.max(dim=-1, keepdim=True)[0] attn_exp = torch.exp(attn - attn_max) ref_unnorm[h] = attn_exp @ vf lse_tensor = torch.zeros(T, 1, 1, dtype=torch.float32, device='cuda') kernel = FmhaKernel(head_dim=hd, s_k=s_k, use_smem_p=False, normalize=False, num_query_heads=n_h, batch_size=1) pv_n_tile = kernel.pv_n_tile stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) # Compile with Q having head dimension v_tile = v[:, 0:pv_n_tile].contiguous() v_kernel = v_tile.unsqueeze(-1) c_tile = torch.zeros(T, 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' Compiling (hd={hd}, n_h={n_h})...', flush=True) compiled = cute.compile(kernel, mQ, mK, mV, mC, stream, mLSE) compiled(mQ, mK, mV, mC, stream, mLSE) torch.cuda.synchronize() # Check output out = o[:, :, :, 0].float() # (n_h, T, hd) cos = torch.nn.functional.cosine_similarity( out.flatten().unsqueeze(0), ref_unnorm.flatten().unsqueeze(0) ).item() print(f' hd={hd}, n_h={n_h}: cos {cos:.6f} {"PASS" if cos >= 0.99 else "FAIL"}') def test(): print("=== D2: Multi-CTA Grid ===\n") test_multi_cta(64, 2) if __name__ == '__main__': test()