D1: add rescale diagnostic

This commit is contained in:
2026-05-24 22:18:12 +00:00
parent 02edff5ac7
commit c33185ca0a

View File

@@ -0,0 +1,103 @@
"""
D1: Minimal TMEM round-trip test.
Strategy: Run the s_k=256 kernel but SKIP the O rescale (force acc_scale=1.0).
This tells us whether the O rescale atoms themselves corrupt data,
or whether the issue is with the acc_scale computation.
If cos with acc_scale=1.0 ≈ 0.8 (same as before), the round-trip is broken.
If cos with acc_scale=1.0 ≈ 0.999, the round-trip works but acc_scale is wrong.
"""
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():
# Test s_k=256 with the kernel — this exercises O rescale
hd = 64
s_k = 256
m = 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()
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
stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
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'Compiling s_k={s_k}...', flush=True)
compiled = cute.compile(kernel, mQ, mK, mV, mC, stream, mLSE)
compiled(mQ, mK, mV, mC, stream, mLSE)
torch.cuda.synchronize()
out = c_tile[:, :, 0].float()
cos_unnorm = torch.nn.functional.cosine_similarity(
out.flatten().unsqueeze(0), ref_unnorm.flatten().unsqueeze(0)
).item()
# Also compare per-row to see pattern
n_bad = 0
for i in range(m):
rc = torch.nn.functional.cosine_similarity(
out[i].unsqueeze(0), ref_unnorm[i].unsqueeze(0)
).item()
if rc < 0.95:
n_bad += 1
if n_bad <= 3:
print(f' Row {i}: cos={rc:.6f} out[:4]={out[i,:4].tolist()} ref[:4]={ref_unnorm[i,:4].tolist()}')
print(f' cos_unnorm={cos_unnorm:.6f} {n_bad}/{m} bad rows (cos<0.95)')
# Now test: does a 1-KV-tile kernel produce perfect output?
kernel1 = FmhaKernel(head_dim=hd, s_k=128, use_smem_p=False, normalize=False)
k1 = k[:128]
c1 = torch.zeros(m, pv_n_tile, 1, dtype=torch.bfloat16, device='cuda')
mK1 = ct.from_dlpack(k1).mark_layout_dynamic(leading_dim=ct.get_leading_dim(k1))
mC1 = ct.from_dlpack(c1).mark_layout_dynamic(leading_dim=ct.get_leading_dim(c1))
ref1_unnorm = (torch.exp(qf @ k1[:, :, 0].float().T * scale -
(qf @ k1[:, :, 0].float().T * scale).max(dim=-1, keepdim=True)[0]) @ v[:128].float())
print(f'Compiling s_k=128...', flush=True)
compiled1 = cute.compile(kernel1, mQ, mK1, mV, mC1, stream, mLSE)
compiled1(mQ, mK1, mV, mC1, stream, mLSE)
torch.cuda.synchronize()
out1 = c1[:, :, 0].float()
cos1 = torch.nn.functional.cosine_similarity(
out1.flatten().unsqueeze(0), ref1_unnorm.flatten().unsqueeze(0)
).item()
print(f' s_k=128: cos_unnorm={cos1:.6f}')
if __name__ == '__main__':
test()