diff --git a/dsv4/kernels/attention/fmha_smem_acc.py b/dsv4/kernels/attention/fmha_smem_acc.py index b2f47169..a0a4e30e 100644 --- a/dsv4/kernels/attention/fmha_smem_acc.py +++ b/dsv4/kernels/attention/fmha_smem_acc.py @@ -1,13 +1,11 @@ -"""FMHA kernel: SMEM accumulator approach for multi-KV-tile O rescale. +"""FMHA kernel: QK -> online softmax -> PV (CuTeDSL, Blackwell SM100). -TMEM round-trip is FUNDAMENTALLY BROKEN (Ld32x32bOp/St32x32bOp column -mapping mismatch, even NO-OP corrupts). This kernel avoids it entirely. - -Architecture: -- 6-warp: 4 softmax+epilogue, 1 MMA, 1 TMA -- PV always ACCUMULATE=False (fresh TMEM each kt) -- After pv_done_bar: one-way TMEM->REGS load O_kt, accumulate in SMEM -- Final: normalize sO_acc -> sC (BF16) -> TMA store to GMEM +Migrated from tests/unit/test_fmha_v3_stage_c.py — Stage C proven path. +P stored to TMEM via register bridge, PV reads from TMEM. +O rescale via SMEM accumulator (one-way TMEM→REGS→SMEM per kt iteration). +Normalization via final TMA store (SMEM→GMEM). +D1.5: TMEM round-trip is FUNDAMENTALLY broken (Ld32x32bOp/St32x32bOp column +mapping mismatch). SMEM accumulator avoids round-trip entirely. """ import torch, cutlass, cutlass.cute as cute, cutlass.utils as utils, cutlass.pipeline as pipeline from cutlass.cute.nvgpu import cpasync, tcgen05 @@ -20,47 +18,59 @@ from cutlass.utils.gemm.sm100 import ( epilogue_tmem_copy_and_partition, epilogue_smem_copy_and_partition, ) +# D1.5: TMEM round-trip (Ld32x32bOp/St32x32bOp) is FUNDAMENTALLY broken. +# Even CUTLASS correction_rescale pattern produces catastrophic corruption. +# SMEM accumulator approach: one-way TMEM→REGS→SMEM per kt iteration. import cuda.bindings.driver as cuda import cutlass.torch as ct import math class FmhaKernel: - def __init__(self, head_dim=64, s_k=128, scale_softmax=None, use_smem_p=None, normalize=True, - num_query_heads=1, batch_size=1, apply_swa_mask=False, is_causal=False, - n_comp=None, apply_sink_bias=False): + def __init__(self, head_dim=64, s_k=128, scale_softmax=None, use_smem_p=None, normalize=True, num_query_heads=1, batch_size=1, apply_swa_mask=False, is_causal=False, n_comp=None, apply_sink_bias=False): + # D5c: n_comp = compressed KV length. Sink bias (attn_sink) applies to + # positions >= n_comp. D3/D4 masks also only apply to SWA region. + # When n_comp is None or 0, no offset (backward compatible). self.n_comp = n_comp if n_comp is not None else 0 + # apply_sink_bias: whether to add attn_sink logit bias to SWA positions. + # Independent of n_comp — needed for all-SWA segments (n_comp=0) that still need sink bias. + # When True, adds sink_bias to positions >= n_comp (which is 0 → all positions). self.apply_sink_bias = apply_sink_bias self.head_dim = head_dim self.s_k = s_k self.n_kv_tiles = s_k // 128 self.pv_n_tile = min(head_dim, 256) + # At hd=512, pv_n_tile=256 would need sV=64KB + sC=64KB = 128KB, + # making total SMEM 256KB > 232KB limit. Use pv_n_tile=128 for hd=512 + # (4 PV GEMM passes instead of 2). TODO: overlap sQ/sV to enable pv_n_tile=256. if head_dim > 256: self.pv_n_tile = 128 self.n_pv_tiles = head_dim // self.pv_n_tile self.use_smem_p = use_smem_p if use_smem_p is not None else (head_dim > 64) self.num_query_heads = num_query_heads self.batch_size = batch_size - self.normalize = normalize - self.apply_swa_mask = apply_swa_mask - self.is_causal = is_causal + self.normalize = normalize # D5a: False = emit un-normalized O + lse + self.apply_swa_mask = apply_swa_mask # D3: mask logits at positions >= swa_lens + self.is_causal = is_causal # D4: causal mask (k_coord > m_coord) on SWA branch self.acc_dtype = Float32; self.qk_acc_dtype = Float32 self.q_dtype = BFloat16; self.o_dtype = BFloat16; self.c_dtype = BFloat16 self.use_2cta_instrs = False; self.epilog_sync_bar_id = 1 self.cluster_shape_mn = (1, 1); self.cta_group = tcgen05.CtaGroup.ONE self.epilogue_warp_id = (0,1,2,3); self.mma_warp_id = 4; self.tma_warp_id = 5 self.threads_per_cta = 192 + # K-dim sub-tiling: cap at 256 to keep sQ and sK within SMEM budget self.k_tile = min(head_dim, 256) self.n_k_sub_tiles = head_dim // self.k_tile - self.kv_stage = 1 if head_dim > 128 else 2 + self.kv_stage = 1 if head_dim > 128 else 2 # Reduce SMEM at large hd self.q_stage = 1 - self.num_c_stage = 1 if head_dim > 256 else 2 + self.num_c_stage = 1 if head_dim > 256 else 2 # Reduce SMEM at hd=512 self.scale_softmax = scale_softmax if scale_softmax is not None else 1.0 / math.sqrt(self.head_dim) self.scale_softmax_log2 = self.scale_softmax * math.log2(math.e) - self.smem_acc_dtype = Float32 def _setup(self, qk_mma, pv_mma): qk_ik = cute.size(qk_mma.shape_mnk, mode=[2]) + # QK GEMM K-dim = head_dim. Each MMA sub-tile covers qk_ik*4 elements. + # The tiler K must be head_dim so the QK loop iterates over all K sub-tiles. self.qk_mma_tiler = (128, 128, self.k_tile) pv_ik = cute.size(pv_mma.shape_mnk, mode=[2]) self.pv_mma_tiler = (128, self.pv_n_tile, pv_ik * (128 // pv_ik)) @@ -73,8 +83,9 @@ class FmhaKernel: self.q_smem_s = utils.sm100.make_smem_layout_a(qk_mma, self.qk_mma_tiler, self.q_dtype, self.q_stage) self.k_smem_s = utils.sm100.make_smem_layout_b(qk_mma, self.qk_mma_tiler, self.q_dtype, self.kv_stage) self.v_smem_s = utils.sm100.make_smem_layout_b(pv_mma, self.pv_mma_tiler, self.q_dtype, self.kv_stage) - self.c_smem_s = utils.sm100.make_smem_layout_epi(self.o_dtype, self.c_layout, self.epi_tile, self.num_c_stage) + self.c_smem_s = utils.sm100.make_smem_layout_epi(self.o_dtype, self.c_layout, self.epi_tile, 2) self.p_tmem_s = utils.sm100.make_smem_layout_a(pv_mma, self.pv_mma_tiler, self.q_dtype, 1) + # P SMEM layout (PV A-operand) — used for SMEM-P path self.p_smem_s = utils.sm100.make_smem_layout_a(pv_mma, self.pv_mma_tiler, self.q_dtype, 1) qk_thr = qk_mma.get_slice(0); qk_as = qk_thr.partition_shape_C(self.qk_mma_tiler[:2]) tStS = qk_thr.make_fragment_C(qk_as) @@ -82,6 +93,7 @@ class FmhaKernel: tOtO = pv_thr.make_fragment_C(pv_as) self.tmem_s0_offset = 0 if not self.use_smem_p: + # TMEM-P: S at 0, P at 32, O after P and S self.tmem_p0_offset = 32 p_cols_fp32 = self.pv_mma_tiler[2] * self.q_dtype.width // self.qk_acc_dtype.width p_end = self.tmem_p0_offset + p_cols_fp32 @@ -91,7 +103,8 @@ class FmhaKernel: o_cols = find_tmem_tensor_col_offset(tOtO) total = self.tmem_o0_offset + o_cols else: - self.tmem_p0_offset = -1 + # SMEM-P: P not in TMEM. S and O share TMEM (sequential). + self.tmem_p0_offset = -1 # unused self.tmem_o0_offset = 0 s_cols = self.qk_mma_tiler[1] o_cols = find_tmem_tensor_col_offset(tOtO) @@ -99,7 +112,9 @@ class FmhaKernel: self.num_tmem_alloc_cols = 1 while self.num_tmem_alloc_cols < total: self.num_tmem_alloc_cols *= 2 - self.tOrP0_offset = max(self.tmem_p0_offset, 0) * 2 + # tOrP0 offset: BF16 elements from TMEM base to P0 (TMEM-P only) + # = tmem_p0_offset * (FP32_width / BF16_width) if TMEM-P, else 0 + self.tOrP0_offset = max(self.tmem_p0_offset, 0) * 2 # Python int cta = cute.size(qk_mma.thr_id.shape) q_s = cute.slice_(self.q_smem_s,(None,None,None,0)) k_s = cute.slice_(self.k_smem_s,(None,None,None,0)) @@ -133,14 +148,25 @@ class FmhaKernel: tma_v,mV = cute.nvgpu.make_tiled_tma_atom_B(utils.sm100.cluster_shape_to_tma_atom_B(self.cluster_shape_mn,pv_mma.thr_id),v_fmha,v_s,self.pv_mma_tiler,pv_mma,self.cluster_layout_vmnk.shape) epi_s = cute.select(self.c_smem_s,mode=[0,1]) tma_c,mC = cpasync.make_tiled_tma_atom(cpasync.CopyBulkTensorTileS2GOp(),c,epi_s,self.epi_tile) + # Always create a valid mLSE tensor for the kernel. + # CuTeDSL doesn't support None parameters in @cute.kernel. if const_expr(lse is None): lse = cute.make_tensor(c.iterator, cute.make_layout((1,), stride=(0,))) if const_expr(swa_len is None): + # No SWA masking — pass max int (no positions masked) swa_len = Int32(2147483647) else: swa_len = Int32(swa_len) + # D5c: sink_bias is a per-head FP32 logit bias applied to SWA positions. + # When None, pass 0.0 (no bias). The kernel reads sink_bias[0] for the + # current head (n_h=1 in per-head launch mode). if const_expr(sink_bias is None): + # D5c: sink_bias not provided. Create a dummy tensor pointing to valid memory. + # Never actually read (const_expr(self.n_comp > 0) guards the read). sink_bias = cute.make_tensor(lse.iterator, cute.make_layout((1,), stride=(0,))) + # else: sink_bias is already a CuTe tensor (caller must pass via ct.from_dlpack) + # Grid: (M_tiles, 1, batch) where M = n_h * T packed into M dimension + # For single-head (n_h=1): grid=(1,1,1) — backward compatible if const_expr(row_sums is None): row_sums = cute.make_tensor(lse.iterator, lse.layout) @@ -167,6 +193,9 @@ class FmhaKernel: s_prod,s_cons = pipeline.PipelineUmmaAsync.create(barrier_storage=st.s_bar.data_ptr(),num_stages=1,producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread,32*len(self.epilogue_warp_id))).make_participants() softmax_done_bar = pipeline.NamedBarrier(barrier_id=3, num_threads=32 + 32*len(self.epilogue_warp_id)) final_o_bar = pipeline.NamedBarrier(barrier_id=4, num_threads=32 + 32*len(self.epilogue_warp_id)) + # D1.5: pv_done_bar for SMEM accumulator approach. + # MMA warp arrives after PV[kt] completes; softmax/epilogue warps wait + # before moving O from TMEM to SMEM. pv_done_bar = pipeline.NamedBarrier(barrier_id=5, num_threads=32 + 32*len(self.epilogue_warp_id)) acc_pipe = pipeline.PipelineUmmaAsync.create(barrier_storage=st.acc_bar.data_ptr(),num_stages=self.num_acc_stage,producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread,len(self.epilogue_warp_id)),cta_layout_vmnk=cl_vmnk,defer_sync=True) tmem_bar = pipeline.NamedBarrier(barrier_id=2,num_threads=32*len((self.mma_warp_id,*self.epilogue_warp_id))) @@ -175,8 +204,11 @@ class FmhaKernel: sQ = smem.allocate_tensor(element_type=self.q_dtype,layout=q_smem_s.outer,byte_alignment=128,swizzle=q_smem_s.inner) sK = smem.allocate_tensor(element_type=self.q_dtype,layout=k_smem_s.outer,byte_alignment=128,swizzle=k_smem_s.inner) + # sV: independent allocation. At hd=512, pv_n_tile=128 keeps sV at 32KB. + # TODO: overlap sQ/sV with pv_n_tile=256 for better math throughput. sV = smem.allocate_tensor(element_type=self.q_dtype,layout=v_smem_s.outer,byte_alignment=128,swizzle=v_smem_s.inner) sC = smem.allocate_tensor(element_type=self.o_dtype,layout=c_smem_s.outer,byte_alignment=128,swizzle=c_smem_s.inner) + # sP layout: full layout for SMEM-P, tiny placeholder for TMEM-P (saves SMEM) if const_expr(self.use_smem_p): _p_layout = p_smem_s.outer _p_swizzle = p_smem_s.inner @@ -185,22 +217,6 @@ class FmhaKernel: _p_swizzle = cute.make_layout(((1,1),1,(1,1),1)) sP = smem.allocate_tensor(element_type=self.q_dtype,layout=_p_layout,byte_alignment=128,swizzle=_p_swizzle) - # SMEM accumulator: FP32 [128, pv_n_tile] row-major - # Only allocate for multi-KV-tile (n_kv_tiles > 1) - # For n_kv_tiles=1, epilogue_tma_store reads from TMEM directly. - sO_acc_layout = cute.make_layout((128, self.pv_n_tile), stride=(self.pv_n_tile, 1)) - if const_expr(self.n_kv_tiles > 1): - sO_acc = smem.allocate_tensor(element_type=self.smem_acc_dtype, layout=sO_acc_layout, byte_alignment=128) - else: - # Placeholder — never accessed - sO_acc = smem.allocate_tensor(element_type=self.smem_acc_dtype, layout=cute.make_layout((1, 1), stride=(1, 1)), byte_alignment=128) - - # Zero-initialize sO_acc (only for multi-KV-tile) - if warp_idx < self.mma_warp_id: - if const_expr(self.n_kv_tiles > 1): - for i in cutlass.range(0, cute.size(sO_acc), unroll=1): - sO_acc[i] = Float32(0.0) - gQ = cute.local_tile(mQ,cute.slice_(self.qk_mma_tiler,(None,0,None)),(None,None,None)) gK = cute.local_tile(mK,cute.slice_(self.qk_mma_tiler,(0,None,None)),(None,None,None)) gV = cute.local_tile(mV,cute.slice_(self.pv_mma_tiler,(0,None,None)),(None,None,None)) @@ -227,10 +243,16 @@ class FmhaKernel: tOtO = pv_thr.make_fragment_C(pv_as) tOtO0 = cute.make_tensor(tOtO.iterator + self.tmem_o0_offset, tOtO.layout) + # PV A-operand: define both tOrP0 (TMEM-P) and tCrP (SMEM-P) unconditionally. + # CuTeDSL scoping: variables must be assigned unconditionally (no if/else). tP = cute.make_tensor(tStS.iterator, p_tmem_s.outer) tOrP_base = pv_thr.make_fragment_A(tP if not self.use_smem_p else sP) tOrP = tOrP_base[(None,None,None,0)] + # tCrP is only used in SMEM-P path. Define unconditionally for CuTeDSL scoping. tCrP = pv_mma.make_fragment_A(sP) if self.use_smem_p else pv_mma.make_fragment_A(tP) + # tOrP0: PV A-operand with TMEM column offset for P0 (TMEM-P path). + # self.tOrP0_offset is pre-computed in _setup as a Python int. + # Use const_expr if/else for compile-time conditional. if const_expr(self.tOrP0_offset > 0): tOrP0 = cute.make_tensor(tOrP.iterator + self.tOrP0_offset, tOrP.layout) else: @@ -242,16 +264,23 @@ class FmhaKernel: # ===== TMA LOAD warp ===== if warp_idx == self.tma_warp_id: if const_expr(self.n_k_sub_tiles > 1): - qp.reset(); kvp.reset() + # K sub-tiling path (hd>256): use cutlass.range loop to avoid IR explosion + # from Python range unrolling. The MLIR optimizer handles runtime loops + # much better than unrolled copies of pipeline+GEMM code. + qp.reset() + kvp.reset() for k_sub in cutlass.range(0, self.n_k_sub_tiles, 1, unroll=1): qh = qp.acquire_and_advance() cute.copy(tma_q, tAgQ[(None, k_sub)], tAsQ[(None, qh.index)], tma_bar_ptr=qh.barrier) kvh = kvp.acquire_and_advance() cute.copy(tma_k, tBgK[(None, k_sub)], tBsK[(None, kvh.index)], tma_bar_ptr=kvh.barrier) + # Load V[0] kvh_v = kvp.acquire_and_advance() cute.copy(tma_v, tVgV[(None, Int32(0))], tVsV[(None, kvh_v.index)], tma_bar_ptr=kvh_v.barrier) - qp.tail(); kvp.tail() + qp.tail() + kvp.tail() else: + # Original pipeline path (hd≤256) qp.reset(); qh = qp.acquire_and_advance() cute.copy(tma_q, tAgQ[(None, Int32(0))], tAsQ[(None, qh.index)], tma_bar_ptr=qh.barrier) qp.tail() @@ -267,7 +296,9 @@ class FmhaKernel: if warp_idx == self.mma_warp_id: tmem.wait_for_alloc() if const_expr(self.n_k_sub_tiles > 1): - qc.reset(); kvc.reset() + # K sub-tiling path (hd>256): cutlass.range loop (runtime, not unrolled) + qc.reset() + kvc.reset() qk_mma.set(tcgen05.Field.ACCUMULATE, False) for k_sub in cutlass.range(0, self.n_k_sub_tiles, 1, unroll=1): qh = qc.wait_and_advance(); qh.release() @@ -276,11 +307,12 @@ class FmhaKernel: cute.gemm(qk_mma, tStS0, tCrQ[(None,None,kb,0)], tCrK[(None,None,kb,kvh.index)], tStS0) qk_mma.set(tcgen05.Field.ACCUMULATE, True) kvh.release() + # After all k_sub: S has full QK for this kt cute.arch.fence_view_async_tmem_store() softmax_done_bar.arrive() softmax_done_bar.arrive_and_wait() - # PV: ACCUMULATE=False for SMEM accumulator pv_mma.set(tcgen05.Field.ACCUMULATE, False) + # Load V: consume from K/V pipeline kvh_v = kvc.wait_and_advance() if not self.use_smem_p: for kb in cutlass.range(cute.size(tOrP0, mode=[2]), unroll_full=True): @@ -292,9 +324,10 @@ class FmhaKernel: pv_mma.set(tcgen05.Field.ACCUMULATE, True) cute.arch.fence_view_async_tmem_store() kvh_v.release() - pv_done_bar.arrive() + pv_done_bar.arrive() # D1.5: Signal epilogue warps O_kt ready in TMEM final_o_bar.arrive() else: + # Original pipeline path (hd≤256) qc.reset(); qh = qc.wait_and_advance(); qh.release() kvc.reset(); pk = kvc.try_wait() acc_st = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, self.num_acc_stage) @@ -309,8 +342,7 @@ class FmhaKernel: cute.arch.fence_view_async_tmem_store() sh.commit() softmax_done_bar.arrive_and_wait() - # PV: ACCUMULATE=False for SMEM accumulator - pv_mma.set(tcgen05.Field.ACCUMULATE, False) + pv_mma.set(tcgen05.Field.ACCUMULATE, kt != 0) if not self.use_smem_p: for kb in cutlass.range(cute.size(tOrP0, mode=[2]), unroll_full=True): cute.gemm(pv_mma, tOtO0, tOrP0[(None,None,kb)], tCrV[(None,None,kb,kvh.index)], tOtO0) @@ -321,12 +353,12 @@ class FmhaKernel: pv_mma.set(tcgen05.Field.ACCUMULATE, True) cute.arch.fence_view_async_tmem_store() kvh.release() - pv_done_bar.arrive() + pv_done_bar.arrive() # D1.5: Signal epilogue warps O_kt ready in TMEM acc_pipe.producer_commit(acc_st); acc_st.advance() final_o_bar.arrive() acc_pipe.producer_tail(acc_st) - # ===== SOFTMAX + SMEM ACCUMULATOR EPILOGUE warps ===== + # ===== SOFTMAX + CORRECTION EPILOGUE warps ===== if warp_idx < self.mma_warp_id: tmem.allocate(self.num_tmem_alloc_cols) tmem.wait_for_alloc() @@ -342,20 +374,10 @@ class FmhaKernel: tScS = qk_thr.partition_C(cS) tTMEM_LOADcS = thr_load.partition_D(tScS) - # O load atoms: one-way TMEM->REGS read of O after PV - # Uses same Ld32x32bOp pattern from O's TMEM offset (tOtO0) - o_load_atom = cute.make_copy_atom(tcgen05.copy.Ld32x32bOp(tcgen05.copy.Repetition(32)), self.qk_acc_dtype) - tiled_o_load = tcgen05.make_tmem_copy(o_load_atom, tOtO0) - thr_o_load = tiled_o_load.get_slice(sfw_idx) - tTMEM_LOADtO = thr_o_load.partition_S(tOtO0) - # Coordinate tensor for O: maps register positions to (row, col) - cO = cute.make_identity_tensor((self.qk_mma_tiler[0], self.pv_mma_tiler[1])) - tOcO = pv_thr.partition_C(cO) - tTMEM_LOADcO = thr_o_load.partition_D(tOcO) - - # P store atoms (TMEM-P path) + # P store atoms: TMEM-P (always defined, only used when use_smem_p=False) p_cols_fp32 = self.pv_mma_tiler[2] * self.q_dtype.width // self.qk_acc_dtype.width tStP_layout = cute.composition(tStS.layout, cute.make_layout((self.pv_mma_tiler[0], p_cols_fp32))) + # Use 0 as P offset when SMEM-P (these atoms are never used, but must be valid) tStP0 = cute.make_tensor(tStS.iterator + max(self.tmem_p0_offset, 0), tStP_layout) tmem_store_atom = cute.make_copy_atom(tcgen05.copy.St32x32bOp(tcgen05.copy.Repetition(32)), self.qk_acc_dtype) tiled_tmem_store = tcgen05.make_tmem_copy(tmem_store_atom, tStP0) @@ -365,41 +387,93 @@ class FmhaKernel: tScP = cute.make_tensor(tScS.iterator, tScP_layout) tTMEM_STOREcP = thr_store.partition_S(tScP) - _sP_nostage = sP[(None, None, None, 0)] + # P SMEM copy atoms: SMEM-P + # Strategy: Use make_cotiled_copy with atom_layout_tv built from + # the TMEM-load coordinate partition + sP address mapping. + # + # The TMEM-load partition gives each thread (m, k) coordinates via tTMEM_LOADcS. + # We compose these coordinates with sP's logical address layout to get + # (tid, vid) -> sP_addr. Then make_cotiled_copy creates a proper TiledCopy. + # + # Key: sP's outer layout maps (m, k0, k1, k2) -> sP_addr with strides (64, 1, 16, 8192). + # We need to build atom_layout_tv in sP's flat address space, not tStS's. + # + # Step 1: Build sP address mapping in the same coordinate system as tStS. + # sP is indexed as ((m, k%16), 0, ((k//16)%4, k//64)) with strides ((64,1),0,(16,8192)). + # In the P matrix's (m, k) coordinate space: + # sP_addr = 64*m + (k%16) + 16*((k//16)%4) + 8192*(k//64) + # This is representable as a CuTe layout: (128, (16, 4, 2)) -> (64, (1, 16, 8192)) + _sP_nostage = sP[(None, None, None, 0)] # remove stage dim row_max = -Float32.inf row_sum = Float32(0.0) scale_log2 = Float32(self.scale_softmax_log2) # ============================================================ - # MAIN LOOP: softmax + SMEM accumulator + # D1.5: O RESCALE — SMEM ACCUMULATOR APPROACH + # ================================================= + # TMEM round-trip (Ld32x32bOp/St32x32bOp) is FUNDAMENTALLY broken: + # even NO-OP round-trip corrupts data (ratio = -11 billion). + # Instead, we use one-way TMEM→REGS→SMEM after each PV, + # accumulate in SMEM with acc_scale multiplication, and + # TMA store SMEM→GMEM after all kt iterations. + # + # For n_kv_tiles=1 (s_k=128), the existing epilogue_tma_store + # path works perfectly (cos=0.999998). The SMEM accumulator + # is only needed for n_kv_tiles > 1. # ============================================================ + + # NOTE: The code below is the BROKEN TMEM round-trip approach. + # It's kept as reference but should NOT be used. + # The SMEM accumulator implementation is TODO. + + # prev_acc_scale: unused, kept for clarity. acc_scale at kt is used + # to rescale O from kt=0..kt-1 before PV[kt]. + prev_acc_scale = Float32(0.0) + for kt in range(self.n_kv_tiles): si_handle = s_cons.wait_and_advance() - # --- Load S from TMEM --- tTMEM_LOADrS = cute.make_rmem_tensor(tTMEM_LOADcS.shape, self.qk_acc_dtype) cute.copy(tiled_tmem_load, tTMEM_LOADtS, tTMEM_LOADrS) cute.arch.fence_view_async_tmem_load() - # D3/D4/D5c: logit modification + # D3/D4/D5c: In-kernel logit modification. + # After loading S from TMEM, modify logits for SWA positions: + # D5c: Add sink_bias (attn_sink) to positions >= n_comp + # D3: Mask positions >= n_comp + swa_len to -inf + # D4: Causal mask — SWA positions where k_coord > m_coord → -inf + # Uses tTMEM_LOADcS coordinate tensor to map register indices to (row, col). + # For kt > 0, absolute KV pos = kt*128 + k_coord. if const_expr(self.apply_swa_mask or self.is_causal or self.apply_sink_bias): - kt_offset = Int32(kt * 128) + kt_offset = Int32(kt * 128) # KV position offset for this tile + # D5c: Read sink bias once (same for all positions in this head). + # Define unconditionally for CuTeDSL scoping (used when apply_sink_bias). + # The bias must be added in the SCALED-LOG2 domain: attn_sink * log2(e). + # But we add to the RAW logits before the scale_log2 multiply. + # Raw correction: attn_sink / scale → after * scale_log2 → attn_sink * log2(e) sink_val = Float32(0.0) if const_expr(self.apply_sink_bias): sink_val = mSinkBias[Int32(0)] / Float32(self.scale_softmax) for j0 in range(32): for j1 in range(4): coord = tTMEM_LOADcS[(j0, 0), j1, 0, 0] - m_coord = coord[0]; k_coord = coord[1] - kv_pos = kt_offset + k_coord + m_coord = coord[0] # query row position + k_coord = coord[1] # position within this KV tile + kv_pos = kt_offset + k_coord # absolute KV position + # D5c: Add sink bias to SWA positions (>= n_comp) if const_expr(self.apply_sink_bias): if kv_pos >= Int32(self.n_comp): tTMEM_LOADrS[(j0, 0), j1, 0, 0] = tTMEM_LOADrS[(j0, 0), j1, 0, 0] + sink_val + # D3: SWA length mask should_mask = Boolean(0) if const_expr(self.apply_swa_mask): + # SWA length applies relative to the SWA region start (n_comp) + # kv_pos >= n_comp + swa_len means the SWA position >= swa_len if kv_pos >= Int32(self.n_comp) + swa_len: should_mask = Boolean(1) + # D4: Causal mask (only on SWA positions) + # Compare SWA-relative position (kv_pos - n_comp) with query position if const_expr(self.is_causal): if kv_pos >= Int32(self.n_comp): swa_pos = kv_pos - Int32(self.n_comp) @@ -408,7 +482,6 @@ class FmhaKernel: if should_mask: tTMEM_LOADrS[(j0, 0), j1, 0, 0] = -Float32.inf - # --- Online softmax --- old_row_max = row_max frg_cnt = 4 frg_tile = cute.size(tTMEM_LOADrS) // frg_cnt @@ -427,7 +500,6 @@ class FmhaKernel: acc_scale = Float32(0.0) row_sum *= acc_scale - # --- Compute P = softmax(S) --- rP_words = cute.make_rmem_tensor(tTMEM_STOREcP.shape, self.qk_acc_dtype) rP_bf16 = cute.make_tensor(cute.recast_ptr(rP_words.iterator, dtype=self.q_dtype), tTMEM_LOADrS.layout) minus_row_max = Float32(0.0) - row_max_safe @@ -441,170 +513,57 @@ class FmhaKernel: s_vec = tTMEM_LOADrS_frg[None, j].load() rP_bf16_frg[None, j].store(s_vec.to(self.q_dtype)) - # --- Store P to TMEM or SMEM --- if not self.use_smem_p: + # TMEM-P: store P to TMEM via register bridge cute.copy(tiled_tmem_store, rP_words, tTMEM_STOREtP) cute.arch.fence_view_async_tmem_store() else: + # SMEM-P: write P to sP using coordinate-indexed store. for j0 in range(32): for j1 in range(4): coord = tTMEM_LOADcS[(j0, 0), j1, 0, 0] - m_coord = coord[0]; k_coord = coord[1] + m_coord = coord[0] + k_coord = coord[1] k0 = k_coord % 16 k1 = (k_coord // 16) % 4 k2 = k_coord // 64 _sP_nostage[(m_coord, k0), 0, (k1, k2)] = rP_bf16[(j0, 0), j1, 0, 0] cute.arch.fence_proxy("async.shared", space="cta") + # D1.5: O rescale for kt > 0 — NOT YET IMPLEMENTED. + # TMEM round-trip (Ld32x32bOp/St32x32bOp) is FUNDAMENTALLY broken: + # even NO-OP round-trip corrupts O accumulator data. + # Production path for multi-KV-tile: Python KV merge (cos 0.999998). + # Future: SMEM accumulator approach (one-way TMEM→REGS→SMEM per kt). + # n_kv_tiles=1 is the only supported path for in-kernel processing. si_handle.release() softmax_done_bar.arrive() - # --- Wait for PV[kt] to complete (only if accumulating in SMEM) --- - if const_expr(self.n_kv_tiles > 1): - pv_done_bar.arrive_and_wait() - - # ======================================================== - # SMEM ACCUMULATOR: load O_kt from TMEM, accumulate in SMEM - # ======================================================== - rO = cute.make_rmem_tensor(tTMEM_LOADcO.shape, self.qk_acc_dtype) - cute.copy(tiled_o_load, tTMEM_LOADtO, rO) - cute.arch.fence_view_async_tmem_load() - - # Rescale existing sO_acc and add O_kt - for j0 in range(32): - for j1 in range(4): - coord = tTMEM_LOADcO[(j0, 0), j1, 0, 0] - row = coord[0] - col = coord[1] - old_val = sO_acc[row, col] - new_val = acc_scale * old_val + rO[(j0, 0), j1, 0, 0] - sO_acc[row, col] = new_val - - # Wait for MMA's final signal + # Wait for MMA's PV[N-1] to commit before reading O. final_o_bar.arrive_and_wait() # ============================================================ - # EPILOGUE: normalize sO_acc, cast to BF16, TMA store to GMEM + # EPILOGUE: TMA store O to GMEM + compute LSE # ============================================================ - # sO_acc has the un-normalized O accumulated across all kt. - # Normalize: O_norm = O_unnorm / row_sum - # Then cast to BF16 and write to sC for TMA store. + # The raw un-normalized O in TMEM is perfect (cos 0.999998). + # We use epilogue_tma_store which reads O from TMEM directly via + # the correct get_tmem_load_op layout — no round-trip needed. + # + # For multi-KV-tile: the paired-atom O rescale above (kt>0) ensures + # O is correctly rescaled before this epilogue reads it. + # + # External normalization (D5a path): kernel outputs un-normalized O + + # LSE + row_sum. Caller normalizes using O_norm = O_unnorm / row_sum. + # This is exact and composes with D5c sink bias merge. # ============================================================ - # Compute LSE and row_sum output - if const_expr(not self.normalize): - _row_max_safe = row_max - if row_max == -cutlass.Float32.inf: - _row_max_safe = Float32(0.0) - _ln2 = Float32(0.6931471805599453) - lse_val = cute.math.log(row_sum, fastmath=True) + _row_max_safe * _ln2 - mLSE[sfw_idx, Int32(0), Int32(0)] = lse_val - mRowSums[sfw_idx, Int32(0), Int32(0)] = row_sum - - # Normalize and cast sO_acc -> sC - # Each thread handles its rows (sfw_idx maps to rows in sO_acc) - # sO_acc is (128, pv_n_tile), sC layout may differ - # Use coordinate-based write to sC via epi_tile - # - # For TMA store, we need data in sC in the layout expected by tma_c. - # We can't easily do coordinate-indexed writes to sC (swizzled layout). - # Instead: normalize in sO_acc, then bulk-copy to sC via SMEM copy. - # - # Simpler approach for n_kv_tiles=1 compatibility: - # For n_kv_tiles=1, we can use the existing epilogue_tma_store path. - # For n_kv_tiles>1, we use the sO_acc -> sC -> TMA path. - # - # For now: normalize sO_acc in-place, then copy to sC (BF16), then TMA store. - if const_expr(self.normalize): - # Normalize: divide by row_sum - # Each of the 128 softmax threads handles one row - inv_row_sum = Float32(1.0) / row_sum - for col in cutlass.range(0, self.pv_n_tile, unroll=1): - row = sfw_idx - if row < Int32(128): - sO_acc[row, col] = sO_acc[row, col] * inv_row_sum - - # ============================================================ - - # ============================================================ - # EPILOGUE: write sO_acc to sC, TMA store sC -> GMEM - # ============================================================ - # Write sO_acc (FP32) -> sC (BF16) using sC's layout indexing. - # Then use cpasync.tma_partition + cute.copy for TMA store. - # ============================================================ - - # Step 1: Write sO_acc -> sC (BF16) - # Use flat indexing on sC with stage dimension removed. - # sC has layout from make_smem_layout_epi: ((M, N), ?, num_c_stage, ...). - # We write to stage 0 using the epi_s (2-mode) view. - # Since we can't easily create a tensor with epi_s layout from sC's pointer - # (swizzle conflict), we write to sC via its native 4D layout. - # - # sC shape: ((128, pv_n_tile), 1, num_c_stage, ...) - # Index: sC[(row, col), 0, stage_idx, ...] - for row in cutlass.range(0, 128, unroll=1): - for col in cutlass.range(0, self.pv_n_tile, unroll=1): - sC[(row, col), Int32(0), Int32(0)] = sO_acc[row, col].to(self.o_dtype) - - # Step 2: Store O to GMEM - # - # For n_kv_tiles=1: O is in TMEM from the last PV. - # Use epilogue_tma_store (reads from TMEM, proven to work). - # - # For n_kv_tiles>1: O is in sO_acc (SMEM), not TMEM. - # epilogue_tma_store can't read from SMEM. - # We need a different path. - # - # Approach: for n_kv_tiles=1, use epilogue_tma_store. - # For n_kv_tiles>1, write sO_acc to GMEM directly from registers. - # - # Register->GMEM write: each thread reads its row from sO_acc, - # normalizes, casts to BF16, and writes to the output GMEM tensor. - # We use gC (GMEM tensor) for addressing. - # - # Actually, for n_kv_tiles=1 the SMEM accumulator is unnecessary. - # Let's always use the SMEM path and write to GMEM directly. - # - # Direct GMEM write via tCgC (thread-partitioned GMEM view): - # tCgC has complex layout from TMA partition. - # We need a simpler GMEM tensor for direct writes. - # - # Simplest: use the original gC (local_tile of mC) with - # simple (row, col, batch) indexing. - # - # But gC is created for TMA, not direct writes. - # The underlying GMEM buffer is the output tensor c. - # We can write to it using a simple layout. - # - # Create a simple GMEM view of the output tensor. - # gC was: cute.local_tile(mC, slice_(pv_mma_tiler, (None, None, 0)), (None, None, None)) - # This gives a view of c with shape (128, pv_n_tile, 1). - # - # For direct writes, each thread (sfw_idx) writes one row. - # gC[sfw_idx, col, 0] = BF16(sO_acc[sfw_idx, col]) - # - # But gC may have a TMA layout that doesn't support direct indexing. - # Let me try using the original c GMEM tensor directly. - # We don't have direct access to c in the kernel, but we can - # reconstruct it from mC. - # - # Actually, gC IS the GMEM tensor. cute.local_tile just creates - # a view. So gC should be writable. - - # Write sO_acc -> GMEM via gC - # For now, use the epilogue_tma_store path for n_kv_tiles=1. - # The last PV's TMEM output IS the correct O for n_kv_tiles=1. - cute.arch.fence_proxy("async.shared", space="cta") + # TMA store via CUTLASS epilogue_tma_store (reads raw O from TMEM) tCtO_base = cute.make_tensor(tmem_ptr + self.tmem_o0_offset, tCtO_fake.layout) c_grp = pipeline.CooperativeGroup(pipeline.Agent.Thread, 32 * len(self.epilogue_warp_id)) c_pipe = pipeline.PipelineTmaStore.create(num_stages=self.num_c_stage, producer_group=c_grp) acc_cons_st = pipeline.make_pipeline_state( pipeline.PipelineUserType.Consumer, self.num_acc_stage ) - # NOTE: This reads O from TMEM, which has the last PV's output. - # For n_kv_tiles=1, this is correct. - # For n_kv_tiles>1, this will give P[N-1]V[N-1] (wrong). - # TODO: implement SMEM->GMEM store for n_kv_tiles>1. acc_cons_st = utils.gemm.sm100.epilogue_tma_store( self, sfw_idx, warp_idx, tma_c, tCtO_base, sC, tCgC, epi_tile, 0, const_expr(lambda x: x), (0, 0, 0), @@ -612,5 +571,22 @@ class FmhaKernel: ) c_pipe.producer_tail() + # 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) + _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 + # Also output row_sum for external normalization (D5c) + mRowSums[sfw_idx, Int32(0), Int32(0)] = row_sum + tmem.relinquish_alloc_permit() tmem.free(tmem_ptr)