diff --git a/dsv4/kernels/attention/fmha.py b/dsv4/kernels/attention/fmha.py index d7a459d7..4b9c956d 100644 --- a/dsv4/kernels/attention/fmha.py +++ b/dsv4/kernels/attention/fmha.py @@ -542,14 +542,17 @@ class FmhaKernel: # Compute LSE: lse = ln(row_sum) + row_max * ln(2) # Only when emitting un-normalized output (D5a path). # When normalize=True, LSE is not needed (in-kernel normalization). + # + # Per-row LSE: each softmax thread (sfw_idx 0..127) handles one row. + # sfw_idx maps directly to the row index in the attention matrix. + # All 128 threads write independently to mLSE[sfw_idx] — no sync needed. if const_expr(not self.normalize): _row_max_safe = row_max if row_max == -cutlass.Float32.inf: _row_max_safe = Float32(0.0) - if sfw_idx == 0: - _ln2 = Float32(0.6931471805599453) # ln(2) - lse_val = cute.math.log(row_sum, fastmath=True) + _row_max_safe * _ln2 - mLSE[0] = lse_val + _ln2 = Float32(0.6931471805599453) # ln(2) + lse_val = cute.math.log(row_sum, fastmath=True) + _row_max_safe * _ln2 + mLSE[sfw_idx, Int32(0), Int32(0)] = lse_val tmem.relinquish_alloc_permit() tmem.free(tmem_ptr) diff --git a/tests/unit/test_d5b_perrow_lse.py b/tests/unit/test_d5b_perrow_lse.py new file mode 100644 index 00000000..e368c1ac --- /dev/null +++ b/tests/unit/test_d5b_perrow_lse.py @@ -0,0 +1,195 @@ +""" +FMHA D5b: Per-row LSE output + Python KV merge. + +Tests that all 128 rows have correct LSE output, enabling accurate +Python-side KV merge for multi-KV-tile scenarios. + +The merge formula (for un-normalized O): + O = (O_unnorm_sparse + exp(attn_sink) * O_unnorm_swa) + / (exp(lse_sparse) + exp(attn_sink) * exp(lse_swa)) + +With per-row LSE, each row can be correctly normalized and merged. + +Run: ~/.openclaw/workspace/fire_b200_test tests/unit/test_d5b_perrow_lse.py +""" +import torch +import 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 reference_attention_with_lse(q, k, v, scale): + """FP32 reference attention returning O and per-row LSE.""" + scores = torch.matmul(q.float(), k.float().T) * scale + max_s = scores.max(dim=-1, keepdim=True).values + exp_s = (scores - max_s).exp() + sum_s = exp_s.sum(dim=-1, keepdim=True) + p = exp_s / sum_s + o = torch.matmul(p, v.float()) + # LSE = ln(sum_s) + max_s (natural log domain) + lse = torch.log(sum_s.squeeze(-1)) + max_s.squeeze(-1) + return o.to(torch.bfloat16), lse + + +def _run_fmha_with_lse(q_3d, k_3d, v, m, s_k, hd, use_smem_p=False): + """Run FMHA and return (o_norm, lse) with per-row LSE.""" + scale = 1.0 / math.sqrt(hd) + kernel = FmhaKernel(head_dim=hd, s_k=s_k, use_smem_p=use_smem_p, 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) + + o_unnorm = torch.zeros(m, hd, dtype=torch.float32, device='cuda') + lse_all = torch.zeros(m, dtype=torch.float32, device='cuda') + + for pv in range(n_pv_tiles): + v_tile = v[:, pv * pv_n_tile:(pv + 1) * pv_n_tile].contiguous().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_3d).mark_layout_dynamic(leading_dim=ct.get_leading_dim(q_3d)) + mK = ct.from_dlpack(k_3d).mark_layout_dynamic(leading_dim=ct.get_leading_dim(k_3d)) + mV = ct.from_dlpack(v_tile).mark_layout_dynamic(leading_dim=ct.get_leading_dim(v_tile)) + 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)) + + if pv == 0: + compiled = cute.compile(kernel, mQ, mK, mV, mC, stream, mLSE) + + compiled(mQ, mK, mV, mC, stream, mLSE) + o_unnorm[:, pv * pv_n_tile:(pv + 1) * pv_n_tile] = c_tile[:, :, 0].float() + lse_all = lse_tensor[:, 0, 0] # Per-row LSE + + # Normalize using per-row LSE + # O_norm = O_unnorm / exp(lse) ... wait, O_unnorm = O_norm * exp(lse) + # So O_norm = O_unnorm / exp(lse).unsqueeze(-1) + o_norm = (o_unnorm / lse_all.exp().unsqueeze(-1)).to(torch.bfloat16) + return o_norm, lse_all + + +def test_lse_per_row_hd64(): + """Per-row LSE at hd=64: all 128 rows should have correct LSE.""" + print("\n=== Test 1: Per-row LSE (hd=64) ===") + torch.manual_seed(42) + m, s_k, hd = 128, 128, 64 + scale = 1.0 / math.sqrt(hd) + + 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') + + o, lse = _run_fmha_with_lse(q, k, v, m, s_k, hd) + ref_o, ref_lse = reference_attention_with_lse(q[:, :, 0], k[:, :, 0], v, scale) + + # Check per-row LSE accuracy + lse_err = (lse - ref_lse).abs().max().item() + print(f" LSE max error: {lse_err:.6f}") + assert lse_err < 0.01, f"LSE error too high: {lse_err}" + + # Check per-row LSE: all rows should be non-zero + zero_rows = (lse == 0).sum().item() + print(f" Zero LSE rows: {zero_rows}") + assert zero_rows == 0, f"Expected 0 zero LSE rows, got {zero_rows}" + + # Check output cosine + cos = torch.nn.functional.cosine_similarity( + o.flatten().float().unsqueeze(0), ref_o.flatten().float().unsqueeze(0) + ).item() + print(f" cos = {cos:.6f}") + assert cos >= 0.995 + print(" ✅ PASS") + + +def test_lse_per_row_hd128(): + """Per-row LSE at hd=128 (SMEM-P path).""" + print("\n=== Test 2: Per-row LSE (hd=128) ===") + torch.manual_seed(42) + m, s_k, hd = 128, 128, 128 + scale = 1.0 / math.sqrt(hd) + + 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') + + o, lse = _run_fmha_with_lse(q, k, v, m, s_k, hd, use_smem_p=True) + ref_o, ref_lse = reference_attention_with_lse(q[:, :, 0], k[:, :, 0], v, scale) + + lse_err = (lse - ref_lse).abs().max().item() + print(f" LSE max error: {lse_err:.6f}") + assert lse_err < 0.01, f"LSE error too high: {lse_err}" + + zero_rows = (lse == 0).sum().item() + print(f" Zero LSE rows: {zero_rows}") + assert zero_rows == 0, f"Expected 0 zero LSE rows, got {zero_rows}" + + cos = torch.nn.functional.cosine_similarity( + o.flatten().float().unsqueeze(0), ref_o.flatten().float().unsqueeze(0) + ).item() + print(f" cos = {cos:.6f}") + assert cos >= 0.995 + print(" ✅ PASS") + + +def test_lse_kv_merge(): + """Python KV merge using per-row LSE (s_k=256, 2 KV tiles).""" + print("\n=== Test 3: KV merge with per-row LSE (s_k=256) ===") + torch.manual_seed(42) + m, s_k, hd = 128, 256, 64 + scale = 1.0 / math.sqrt(hd) + + 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') + + # Reference: full attention with s_k=256 + ref_o, _ = reference_attention_with_lse(q[:, :, 0], k[:, :, 0], v, scale) + + # Kernel: two segments of 128, merge with per-row LSE + seg_size = 128 + o_merged = torch.zeros(m, hd, dtype=torch.float32, device='cuda') + lse_max = None + weighted_sum = None + + for seg in range(s_k // seg_size): + k_seg = k[seg * seg_size:(seg + 1) * seg_size] + v_seg = v[seg * seg_size:(seg + 1) * seg_size] + k_seg_3d = k_seg.unsqueeze(-1) + + o_seg, lse_seg = _run_fmha_with_lse(q, k_seg_3d, v_seg, m, seg_size, hd) + o_seg_f = o_seg.float() + lse_seg_f = lse_seg.float() + + if lse_max is None: + lse_max = lse_seg_f + weighted_sum = lse_seg_f.exp().unsqueeze(-1) * o_seg_f + else: + # Online merge: O = (exp(lse0)*O0 + exp(lse1)*O1) / (exp(lse0) + exp(lse1)) + new_lse_max = torch.max(lse_max, lse_seg_f) + # Rescale existing + scale0 = (lse_max - new_lse_max).exp() + scale1 = (lse_seg_f - new_lse_max).exp() + weighted_sum = scale0.unsqueeze(-1) * weighted_sum + scale1.unsqueeze(-1) * lse_seg_f.exp().unsqueeze(-1) * o_seg_f + lse_max = new_lse_max + + o_merged = (weighted_sum / lse_max.exp().unsqueeze(-1)).to(torch.bfloat16) + + cos = torch.nn.functional.cosine_similarity( + o_merged.flatten().float().unsqueeze(0), ref_o.flatten().float().unsqueeze(0) + ).item() + print(f" cos = {cos:.6f}") + assert cos >= 0.99, f"cosine too low: {cos}" + print(" ✅ PASS") + + +def test(): + print("=== D5b: Per-Row LSE Output ===") + test_lse_per_row_hd64() + test_lse_per_row_hd128() + test_lse_kv_merge() + print("\n=== ALL TESTS PASSED ===") + + +if __name__ == '__main__': + test()