Files
nvfp4-megamoe-kernel/tests/unit/test_d1_kv_merge.py

120 lines
4.8 KiB
Python

"""
D1: Test multi-KV-tile by running s_k=128 kernel per KV segment and
merging in Python using log-sum-exp (D5 merge formula).
This avoids the broken TMEM round-trip O rescale entirely.
"""
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_merge(hd=64, s_k=256):
m = 128
n_kv_segments = 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')
# FP32 reference (full attention)
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_norm = (attn_exp / attn_sum) @ v.float()
# Run s_k=128 kernel per KV segment and merge using log-sum-exp
kernel = FmhaKernel(head_dim=hd, s_k=128, 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 once with segment 0's K
k_seg = k[:128]
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')
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_seg).mark_layout_dynamic(leading_dim=ct.get_leading_dim(k_seg))
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}, s_k=128 per segment, {n_kv_segments} segments)...', flush=True)
compiled = cute.compile(kernel, mQ, mK, mV, mC, stream, mLSE)
# Accumulate across KV segments using log-sum-exp merge
# O_merged = sum_i(exp(lse_i) * O_i) / sum_i(exp(lse_i))
o_accum = torch.zeros(m, hd, dtype=torch.float32, device='cuda')
lse_accum = torch.full((m, 1), float('-inf'), dtype=torch.float32, device='cuda')
for seg in range(n_kv_segments):
k_start = seg * 128
k_end = k_start + 128
k_seg = k[k_start:k_end]
v_seg = v[k_start:k_end]
# Per-segment O and LSE
seg_o = torch.zeros(m, hd, dtype=torch.float32, device='cuda')
seg_lse = torch.zeros(m, 1, dtype=torch.float32, device='cuda')
for nt in range(n_pv_tiles):
v_start = nt * pv_n_tile
v_end = v_start + pv_n_tile
v_tile = v_seg[:, 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_seg).mark_layout_dynamic(leading_dim=ct.get_leading_dim(k_seg))
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()
seg_o[:, v_start:v_end] = c_tile[:, :, 0].float()
if nt == 0:
seg_lse[:, 0] = lse_tensor[:, 0, 0].float()
# Merge with accumulator using log-sum-exp
# O_new = (exp(lse_old) * O_old + exp(lse_new) * O_new) / (exp(lse_old) + exp(lse_new))
# lse_new = ln(exp(lse_old) + exp(lse_new))
e_old = torch.exp(lse_accum) # (m, 1)
e_new = torch.exp(seg_lse) # (m, 1)
e_sum = e_old + e_new
o_accum = (e_old * o_accum + e_new * seg_o) / e_sum
lse_accum = torch.log(e_sum)
cos = torch.nn.functional.cosine_similarity(
o_accum.flatten().unsqueeze(0), ref_norm.flatten().unsqueeze(0)
).item()
print(f' hd={hd}, s_k={s_k} ({n_kv_segments} segments): cos_norm {cos:.6f} {"PASS" if cos >= 0.99 else "FAIL"}')
return cos
def test():
print("=== D1: Multi-KV Merge via Log-Sum-Exp (no TMEM round-trip) ===\n")
test_multi_kv_merge(64, 256)
test_multi_kv_merge(64, 384)
test_multi_kv_merge(64, 512)
test_multi_kv_merge(64, 1024)
test_multi_kv_merge(128, 256)
if __name__ == '__main__':
test()