"""Quick D1 regression test: HEAD_DIM=64 only, must match Stage C. Kernel outputs un-normalized O + LSE (D5a path).""" 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(): torch.manual_seed(42) hd, n = 64, 128 m = 128 q = torch.randn(m, hd, 1, dtype=torch.bfloat16, device='cuda') k = torch.randn(n, hd, 1, dtype=torch.bfloat16, device='cuda') v = torch.randn(n, hd, dtype=torch.bfloat16, device='cuda') v_kernel = v.unsqueeze(-1) c = torch.zeros(m, hd, 1, dtype=torch.bfloat16, device='cuda') # FP32 reference (un-normalized + normalized) 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() lse_tensor = torch.zeros(m, 1, 1, dtype=torch.float32, 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).mark_layout_dynamic(leading_dim=ct.get_leading_dim(c)) mLSE = ct.from_dlpack(lse_tensor).mark_layout_dynamic(leading_dim=ct.get_leading_dim(lse_tensor)) stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream) # normalize=False: kernel outputs un-normalized O + LSE kernel = FmhaKernel(head_dim=hd, s_k=n, normalize=False) print(f'hd={hd}, n={n}: Compiling...', flush=True) compiled = cute.compile(kernel, mQ, mK, mV, mC, stream, mLSE) compiled(mQ, mK, mV, mC, stream, mLSE) torch.cuda.synchronize() out_unnorm = c[:, :, 0].float() out_norm = out_unnorm / attn_sum # external normalization using row_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() print(f'hd={hd}, n={n}: cos_unnorm {cos_unnorm:.6f} cos_norm {cos_norm:.6f} {"PASS" if cos_norm >= 0.99 else "FAIL"}') if __name__ == '__main__': test()