more stuff
This commit is contained in:
351
tests/native_stage_c_patch.py
Normal file
351
tests/native_stage_c_patch.py
Normal file
@@ -0,0 +1,351 @@
|
||||
"""
|
||||
Native Blackwell Stage-C drop-in implementation for FmhaV3.
|
||||
|
||||
This file is intentionally a patch module rather than a second full copy of the
|
||||
whole test. It contains the exact role layout, pipeline definitions, and the
|
||||
native correction helpers to splice into your current test_fmha_v3.py / Stage-B
|
||||
kernel.
|
||||
|
||||
Architecture:
|
||||
softmax warps 0-3 : S(TMEM) -> P(TMEM), vec(TMEM)
|
||||
correction warps 4-7 : vec(TMEM) + O(TMEM) -> corrected O(SMEM)
|
||||
MMA warp 8 : QK and PV
|
||||
TMA/load warp 9 : Q/K/V load
|
||||
epilogue warp 10 : corrected O SMEM -> GMEM
|
||||
empty warp 11 : tmem dealloc mbar init/helper
|
||||
|
||||
The key design decision: softmax NEVER rescales O. Correction is the only code
|
||||
path that touches O for online rescale/final normalization. Epilogue never
|
||||
reads TMEM.
|
||||
"""
|
||||
|
||||
# -------------------------
|
||||
# 1) role layout
|
||||
# -------------------------
|
||||
# Put this in __init__
|
||||
SOFTMAX_WARP_IDS = (0, 1, 2, 3)
|
||||
CORRECTION_WARP_IDS = (4, 5, 6, 7)
|
||||
MMA_WARP_ID = 8
|
||||
TMA_WARP_ID = 9
|
||||
EPILOGUE_WARP_ID = 10
|
||||
EMPTY_WARP_ID = 11
|
||||
THREADS_PER_CTA = 32 * 12
|
||||
|
||||
# Pipeline stages to add to your class
|
||||
MMA_SOFTMAX_STAGE = 1
|
||||
SOFTMAX_CORR_STAGE = 1
|
||||
MMA_CORR_STAGE = 2
|
||||
EPI_STAGE = 2
|
||||
|
||||
# TMEM offsets for a single 128x128 S/P tile and 128x64 O tile.
|
||||
# vec reuses S region only after the S tile has been loaded by softmax.
|
||||
TMEM_S0_OFFSET = 0
|
||||
TMEM_VEC0_OFFSET = 0
|
||||
TMEM_P0_OFFSET = 32
|
||||
TMEM_O0_OFFSET = 128
|
||||
|
||||
|
||||
# -------------------------
|
||||
# 2) shared storage fields
|
||||
# -------------------------
|
||||
SHARED_STORAGE_FIELDS = r'''
|
||||
@cute.struct
|
||||
class SS:
|
||||
q_bar: cute.struct.MemRange[cutlass.Int64, self.q_stage * 2]
|
||||
kv_bar: cute.struct.MemRange[cutlass.Int64, self.kv_stage * 2]
|
||||
mma_s_bar: cute.struct.MemRange[cutlass.Int64, self.mma_softmax_stage * 2]
|
||||
s_corr_bar: cute.struct.MemRange[cutlass.Int64, self.softmax_corr_stage * 2]
|
||||
mma_corr_bar: cute.struct.MemRange[cutlass.Int64, self.mma_corr_stage * 2]
|
||||
corr_epi_bar: cute.struct.MemRange[cutlass.Int64, self.epi_stage * 2]
|
||||
tmem_dealloc: cute.struct.MemRange[cutlass.Int64, 1]
|
||||
holding: cutlass.Int32
|
||||
'''
|
||||
|
||||
|
||||
# -------------------------
|
||||
# 3) pipeline creation
|
||||
# -------------------------
|
||||
PIPELINE_CREATION = r'''
|
||||
def cg_threads(n: int):
|
||||
return pipeline.CooperativeGroup(pipeline.Agent.Thread, n)
|
||||
|
||||
q_prod, q_cons = pipeline.PipelineTmaUmma.create(
|
||||
barrier_storage=st.q_bar.data_ptr(),
|
||||
num_stages=self.q_stage,
|
||||
producer_group=cg_threads(1),
|
||||
consumer_group=cg_threads(1),
|
||||
tx_count=self.q_tx_bytes,
|
||||
cta_layout_vmnk=cl_vmnk,
|
||||
defer_sync=True,
|
||||
).make_participants()
|
||||
|
||||
kv_prod, kv_cons = pipeline.PipelineTmaUmma.create(
|
||||
barrier_storage=st.kv_bar.data_ptr(),
|
||||
num_stages=self.kv_stage,
|
||||
producer_group=cg_threads(1),
|
||||
consumer_group=cg_threads(1),
|
||||
tx_count=self.kv_tx_bytes,
|
||||
cta_layout_vmnk=cl_vmnk,
|
||||
defer_sync=True,
|
||||
).make_participants()
|
||||
|
||||
# MMA publishes S; softmax consumes S and releases the handle only after P is ready.
|
||||
mma_s_prod, mma_s_cons = pipeline.PipelineUmmaAsync.create(
|
||||
barrier_storage=st.mma_s_bar.data_ptr(),
|
||||
num_stages=self.mma_softmax_stage,
|
||||
producer_group=cg_threads(1),
|
||||
consumer_group=cg_threads(32 * len(self.softmax_warp_ids)),
|
||||
cta_layout_vmnk=cl_vmnk,
|
||||
defer_sync=True,
|
||||
).make_participants()
|
||||
|
||||
# Softmax publishes vec[row] = [old_max,new_max] each tile and [row_sum,row_max] at final.
|
||||
s_corr_prod, s_corr_cons = pipeline.PipelineAsync.create(
|
||||
barrier_storage=st.s_corr_bar.data_ptr(),
|
||||
num_stages=self.softmax_corr_stage,
|
||||
producer_group=cg_threads(32 * len(self.softmax_warp_ids)),
|
||||
consumer_group=cg_threads(32 * len(self.correction_warp_ids)),
|
||||
).make_participants()
|
||||
|
||||
# MMA publishes O after each PV. Correction consumes O for online rescale / final epilog.
|
||||
mma_corr_prod, mma_corr_cons = pipeline.PipelineUmmaAsync.create(
|
||||
barrier_storage=st.mma_corr_bar.data_ptr(),
|
||||
num_stages=self.mma_corr_stage,
|
||||
producer_group=cg_threads(1),
|
||||
consumer_group=cg_threads(32 * len(self.correction_warp_ids)),
|
||||
cta_layout_vmnk=cl_vmnk,
|
||||
defer_sync=True,
|
||||
).make_participants()
|
||||
|
||||
# Correction publishes final converted O in SMEM; epilogue warp TMA-stores it.
|
||||
corr_epi_prod, corr_epi_cons = pipeline.PipelineAsync.create(
|
||||
barrier_storage=st.corr_epi_bar.data_ptr(),
|
||||
num_stages=self.epi_stage,
|
||||
producer_group=cg_threads(32 * len(self.correction_warp_ids)),
|
||||
consumer_group=cg_threads(32),
|
||||
).make_participants()
|
||||
|
||||
# TMEM allocation/retrieve participants are softmax + correction + MMA only.
|
||||
tmem_bar = pipeline.NamedBarrier(
|
||||
barrier_id=2,
|
||||
num_threads=32 * len((*self.softmax_warp_ids, *self.correction_warp_ids, self.mma_warp_id)),
|
||||
)
|
||||
tmem = utils.TmemAllocator(
|
||||
st.holding.ptr,
|
||||
barrier_for_retrieve=tmem_bar,
|
||||
allocator_warp_id=self.softmax_warp_ids[0],
|
||||
is_two_cta=cute.size(qk_mma.thr_id.shape) == 2,
|
||||
two_cta_tmem_dealloc_mbar_ptr=st.tmem_dealloc.ptr,
|
||||
)
|
||||
|
||||
# Deallocation mbarrier is NOT a named barrier. Only softmax+correction arrive;
|
||||
# MMA waits and deallocates after relinquish_tmem_alloc_permit().
|
||||
if warp_idx == self.empty_warp_id:
|
||||
cute.arch.mbarrier_init(
|
||||
st.tmem_dealloc.data_ptr(),
|
||||
32 * len((*self.softmax_warp_ids, *self.correction_warp_ids)),
|
||||
)
|
||||
cute.arch.mbarrier_init_fence()
|
||||
'''
|
||||
|
||||
|
||||
# -------------------------
|
||||
# 4) correction helpers
|
||||
# -------------------------
|
||||
CORRECTION_HELPERS = r'''
|
||||
@cute.jit
|
||||
def correction_rescale(self, pv_thr, tOtO, scale: Float32):
|
||||
"""Correction warpgroup: O[row,:] *= scale[row]. O stays in TMEM."""
|
||||
cO = cute.make_identity_tensor((self.pv_mma_tiler[0], self.pv_mma_tiler[1]))
|
||||
tOcO = pv_thr.partition_C(cO)
|
||||
|
||||
corr_tile_size = 16
|
||||
tmem_load_atom = cute.make_copy_atom(
|
||||
tcgen05.copy.Ld32x32bOp(tcgen05.copy.Repetition(corr_tile_size)),
|
||||
self.pv_acc_dtype,
|
||||
)
|
||||
tmem_store_atom = cute.make_copy_atom(
|
||||
tcgen05.copy.St32x32bOp(tcgen05.copy.Repetition(corr_tile_size)),
|
||||
self.pv_acc_dtype,
|
||||
)
|
||||
|
||||
tOtO_i_layout = cute.composition(tOtO.layout, cute.make_layout((128, corr_tile_size)))
|
||||
tOcO_i_layout = cute.composition(tOcO.layout, cute.make_layout((128, corr_tile_size)))
|
||||
tOtO_i = cute.make_tensor(tOtO.iterator, tOtO_i_layout)
|
||||
tOcO_i = cute.make_tensor(tOcO.iterator, tOcO_i_layout)
|
||||
|
||||
tiled_tmem_load = tcgen05.make_tmem_copy(tmem_load_atom, tOtO_i)
|
||||
tiled_tmem_store = tcgen05.make_tmem_copy(tmem_store_atom, tOtO_i)
|
||||
|
||||
tidx, _, _ = cute.arch.thread_idx()
|
||||
thread_idx = tidx % (32 * len(self.correction_warp_ids))
|
||||
thr_load = tiled_tmem_load.get_slice(thread_idx)
|
||||
thr_store = tiled_tmem_store.get_slice(thread_idx)
|
||||
|
||||
tTMEM_LOADtO = thr_load.partition_S(tOtO_i)
|
||||
tTMEM_LOADcO = thr_load.partition_D(tOcO_i)
|
||||
tTMEM_STOREtO = thr_store.partition_D(tOtO_i)
|
||||
|
||||
o_col_tiles = self.pv_mma_tiler[1] // corr_tile_size
|
||||
tTMrO = cute.make_rmem_tensor((tTMEM_LOADcO.shape, o_col_tiles), self.pv_acc_dtype)
|
||||
for i in range(o_col_tiles):
|
||||
tTMrO_i_ = tTMrO[None, i]
|
||||
tTMrO_i_layout = cute.composition(tTMrO_i_.layout, cute.make_layout(tTMrO.shape[0]))
|
||||
tTMrO_i = cute.make_tensor(tTMrO_i_.iterator, tTMrO_i_layout)
|
||||
tTMEM_LOADtO_i = cute.make_tensor(tTMEM_LOADtO.iterator + i * corr_tile_size, tTMEM_LOADtO.layout)
|
||||
tTMEM_STOREtO_i = cute.make_tensor(tTMEM_STOREtO.iterator + i * corr_tile_size, tTMEM_STOREtO.layout)
|
||||
cute.copy(tiled_tmem_load, tTMEM_LOADtO_i, tTMrO_i)
|
||||
for j in cutlass.range(cute.size(tTMrO_i), vectorize=True):
|
||||
tTMrO_i[j] = tTMrO_i[j] * scale
|
||||
cute.copy(tiled_tmem_store, tTMrO_i, tTMEM_STOREtO_i)
|
||||
|
||||
|
||||
@cute.jit
|
||||
def correction_epilog(self, pv_thr, tOtO, scale: Float32, sO):
|
||||
"""Correction final: load O from TMEM, normalize/convert, write SMEM."""
|
||||
cO = cute.make_identity_tensor((self.pv_mma_tiler[0], self.pv_mma_tiler[1]))
|
||||
corr_tile_size = 32 * 8 // self.o_dtype.width
|
||||
|
||||
tOsO = pv_thr.partition_C(sO)
|
||||
tOcO = pv_thr.partition_C(cO)
|
||||
tOtO_i = cute.logical_divide(tOtO, cute.make_layout((128, corr_tile_size)))
|
||||
tOcO_i = cute.logical_divide(tOcO, cute.make_layout((128, corr_tile_size)))
|
||||
tOsO_i = cute.logical_divide(tOsO, cute.make_layout((128, corr_tile_size)))
|
||||
|
||||
tidx, _, _ = cute.arch.thread_idx()
|
||||
thread_idx = tidx % (32 * len(self.correction_warp_ids))
|
||||
epi_subtile = (self.epi_tile[0], corr_tile_size)
|
||||
|
||||
tmem_copy_atom = utils.sm100.get_tmem_load_op(
|
||||
self.pv_mma_tiler,
|
||||
self.c_layout,
|
||||
self.o_dtype,
|
||||
self.pv_acc_dtype,
|
||||
epi_subtile,
|
||||
use_2cta_instrs=False,
|
||||
)
|
||||
tiled_tmem_load = tcgen05.make_tmem_copy(tmem_copy_atom, tOtO_i[(None, None), 0])
|
||||
thr_tmem_load = tiled_tmem_load.get_slice(thread_idx)
|
||||
|
||||
smem_copy_atom = utils.sm100.get_smem_store_op(
|
||||
self.c_layout,
|
||||
self.o_dtype,
|
||||
self.pv_acc_dtype,
|
||||
tiled_tmem_load,
|
||||
)
|
||||
tiled_smem_store = cute.make_tiled_copy_D(smem_copy_atom, tiled_tmem_load)
|
||||
|
||||
tTMEM_LOADtO = thr_tmem_load.partition_S(tOtO_i[(None, None), None])
|
||||
tTMEM_LOADsO = thr_tmem_load.partition_D(tOsO_i[(None, None), None])
|
||||
tTMEM_LOADoO = thr_tmem_load.partition_D(tOcO_i[(None, None), None])
|
||||
|
||||
for i in range(self.pv_mma_tiler[1] // corr_tile_size):
|
||||
tTMrO = cute.make_rmem_tensor(tTMEM_LOADoO[None, 0, 0, i].shape, self.pv_acc_dtype)
|
||||
cute.copy(tiled_tmem_load, tTMEM_LOADtO[None, 0, 0, i], tTMrO)
|
||||
for j in cutlass.range(cute.size(tTMrO), vectorize=True):
|
||||
tTMrO[j] = tTMrO[j] * scale
|
||||
tSMrO = cute.make_rmem_tensor(tTMrO.shape, self.o_dtype)
|
||||
tSMrO.store(tTMrO.load().to(self.o_dtype))
|
||||
cute.copy(tiled_smem_store, tSMrO, tTMEM_LOADsO[None, 0, 0, i])
|
||||
|
||||
cute.arch.fence_proxy("async.shared", space="cta")
|
||||
'''
|
||||
|
||||
|
||||
# -------------------------
|
||||
# 5) native Stage-C flow
|
||||
# -------------------------
|
||||
NATIVE_STAGE_C_FLOW = r'''
|
||||
# MMA loop pseudocode, replacing softmax_done_bar/pv_done_bar:
|
||||
if is_mma:
|
||||
tmem.wait_for_alloc()
|
||||
... load Q/K/V pipeline setup ...
|
||||
s_state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, self.mma_softmax_stage)
|
||||
o_state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, self.mma_corr_stage)
|
||||
mma_s_prod.producer_acquire(s_state)
|
||||
mma_corr_prod.producer_acquire(o_state)
|
||||
for kt in range(n_kv_tiles):
|
||||
# QK -> S
|
||||
... cute.gemm(qk_mma, ..., tStS0) ...
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
mma_s_prod.producer_commit(s_state)
|
||||
s_state.advance()
|
||||
|
||||
# IMPORTANT: there is no named barrier here. The softmax consumer releases
|
||||
# the same S handle only after P has been stored, so this is P-ready.
|
||||
if kt + 1 < n_kv_tiles:
|
||||
mma_s_prod.producer_acquire(s_state)
|
||||
|
||||
# PV -> O
|
||||
... cute.gemm(pv_mma, tOtO0, tOrP0, V, tOtO0) ...
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
mma_corr_prod.producer_commit(o_state)
|
||||
o_state.advance()
|
||||
if kt + 1 < n_kv_tiles:
|
||||
mma_corr_prod.producer_acquire(o_state)
|
||||
mma_s_prod.producer_tail(s_state)
|
||||
mma_corr_prod.producer_tail(o_state)
|
||||
|
||||
cute.arch.relinquish_tmem_alloc_permit()
|
||||
cute.arch.mbarrier_wait(st.tmem_dealloc.data_ptr(), 0)
|
||||
tmem_ptr = cute.arch.retrieve_tmem_ptr(self.qk_acc_dtype, alignment=16, ptr_to_buffer_holding_addr=st.holding.ptr)
|
||||
cute.arch.dealloc_tmem(tmem_ptr, Int32(self.num_tmem_alloc_cols))
|
||||
|
||||
|
||||
# Softmax loop:
|
||||
if is_softmax:
|
||||
tmem.allocate(self.num_tmem_alloc_cols)
|
||||
tmem.wait_for_alloc()
|
||||
vec_handle = s_corr_prod.acquire_and_advance()
|
||||
row_max = -Float32.inf
|
||||
row_sum = Float32(0.0)
|
||||
for kt in range(n_kv_tiles):
|
||||
si = mma_s_cons.wait_and_advance()
|
||||
# load S, compute old/new row max, store vec=[old_max,new_max]
|
||||
# compute P=exp2((S-new_max)*scale), store P to TMEM
|
||||
# update row_sum
|
||||
vec_handle.commit()
|
||||
si.release() # P-ready signal to MMA
|
||||
vec_handle = s_corr_prod.acquire_and_advance()
|
||||
# final vec=[row_sum,row_max]
|
||||
final_si = mma_s_cons.wait_and_advance()
|
||||
... store final vec ...
|
||||
vec_handle.commit()
|
||||
s_corr_prod.acquire() # balance final pipe step
|
||||
final_si.release()
|
||||
cute.arch.mbarrier_arrive(st.tmem_dealloc.data_ptr())
|
||||
|
||||
|
||||
# Correction loop:
|
||||
if is_correction:
|
||||
tmem.wait_for_alloc()
|
||||
first_vec = s_corr_cons.wait_and_advance()
|
||||
first_vec.release() # first tile has no previous O to rescale
|
||||
for kt in range(n_kv_tiles - 1):
|
||||
vec = s_corr_cons.wait_and_advance()
|
||||
... load [old_max,new_max] ...
|
||||
scale = exp2(scale_log2 * (old_max - new_max))
|
||||
o = mma_corr_cons.wait_and_advance()
|
||||
self.correction_rescale(pv_thr, tOtO0, scale)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
o.release()
|
||||
vec.release()
|
||||
final_vec = s_corr_cons.wait_and_advance()
|
||||
... load [row_sum,row_max] ...
|
||||
final_vec.release()
|
||||
final_o = mma_corr_cons.wait_and_advance()
|
||||
epi = corr_epi_prod.acquire_and_advance()
|
||||
self.correction_epilog(pv_thr, tOtO0, self.scale_output / row_sum, sC[(None, None, epi.index)])
|
||||
final_o.release()
|
||||
epi.commit()
|
||||
cute.arch.mbarrier_arrive(st.tmem_dealloc.data_ptr())
|
||||
|
||||
|
||||
# Epilogue warp:
|
||||
if is_epi:
|
||||
h = corr_epi_cons.wait_and_advance()
|
||||
cute.copy(tma_c, tCsC[(None, h.index)], tCgC_epi[(None, 0)])
|
||||
cute.arch.cp_async_bulk_commit_group()
|
||||
cute.arch.cp_async_bulk_wait_group(0, read=True)
|
||||
h.release()
|
||||
'''
|
||||
327
tests/unit/test_fmha_v3_12w.py
Normal file
327
tests/unit/test_fmha_v3_12w.py
Normal file
@@ -0,0 +1,327 @@
|
||||
"""
|
||||
FMHA v3: QK -> softmax -> PV with KV-tile interleaving.
|
||||
Bug 4b fix (FMHA pattern): P store uses QK C-fragment layout composition,
|
||||
NOT PV A-fragment layout. Register bridge: FP32 backing (store partition shape)
|
||||
recast to BF16 view (QK-load layout).
|
||||
"""
|
||||
import torch, cutlass, cutlass.cute as cute, cutlass.utils as utils, cutlass.pipeline as pipeline
|
||||
from cutlass.cute.nvgpu import cpasync, tcgen05
|
||||
from cutlass import Float32, BFloat16, Int32, Boolean, const_expr
|
||||
from cutlass.utils import LayoutEnum
|
||||
from cutlass.utils.tmem_allocator import find_tmem_tensor_col_offset
|
||||
import cuda.bindings.driver as cuda
|
||||
import cutlass.torch as ct
|
||||
|
||||
HEAD_DIM = 64
|
||||
|
||||
class FmhaV3:
|
||||
def __init__(self):
|
||||
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; self.num_c_stage = 2
|
||||
self.kv_stage = 2; self.q_stage = 1; self.num_c_stage = 2
|
||||
|
||||
def _setup(self, qk_mma, pv_mma):
|
||||
qk_ik = cute.size(qk_mma.shape_mnk, mode=[2])
|
||||
self.qk_mma_tiler = (128, 128, qk_ik * 4)
|
||||
pv_ik = cute.size(pv_mma.shape_mnk, mode=[2])
|
||||
self.pv_mma_tiler = (128, HEAD_DIM, pv_ik * (128 // pv_ik))
|
||||
self.mma_tiler = self.qk_mma_tiler
|
||||
self.cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((1,1,1)), (qk_mma.thr_id.shape,))
|
||||
self.cta_tile_shape_mnk = (self.qk_mma_tiler[0]//cute.size(qk_mma.thr_id.shape), HEAD_DIM, self.qk_mma_tiler[2])
|
||||
self.c_layout = LayoutEnum.ROW_MAJOR
|
||||
self.epi_tile = utils.sm100.compute_epilogue_tile_shape(self.cta_tile_shape_mnk, False, self.c_layout, self.o_dtype)
|
||||
self.num_ab_stage = 1; self.num_acc_stage = 1
|
||||
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, 2)
|
||||
self.p_tmem_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)
|
||||
pv_thr = pv_mma.get_slice(0); pv_as = pv_thr.partition_shape_C(self.pv_mma_tiler[:2])
|
||||
tOtO = pv_thr.make_fragment_C(pv_as)
|
||||
self.tmem_s0_offset = 0; self.tmem_p0_offset = 32
|
||||
# P occupies [tmem_p0_offset, tmem_p0_offset + p_cols_fp32)
|
||||
# S occupies [0, qk_mma_tiler[1]) = [0, 128)
|
||||
# O must NOT overlap P. Place O after max(S end, P end), aligned to 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 # 32 + 64 = 96
|
||||
s_cols = self.qk_mma_tiler[1] # 128
|
||||
o_after = max(s_cols, p_end) # 128
|
||||
self.tmem_o0_offset = ((o_after + 31) // 32) * 32 # align to 32 = 128
|
||||
o_cols = find_tmem_tensor_col_offset(tOtO) # footprint of O
|
||||
total = self.tmem_o0_offset + o_cols
|
||||
# Must be multiple of 32 AND power of 2
|
||||
self.num_tmem_alloc_cols = 1
|
||||
while self.num_tmem_alloc_cols < total:
|
||||
self.num_tmem_alloc_cols *= 2
|
||||
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))
|
||||
self.q_tx_bytes = cute.size_in_bytes(self.q_dtype, q_s) * cta
|
||||
self.kv_tx_bytes = cute.size_in_bytes(self.q_dtype, k_s) * cta
|
||||
|
||||
@cute.jit
|
||||
def __call__(self, q, k, v, c, stream):
|
||||
self.q_dtype = q.element_type; self.o_dtype = c.element_type; self.c_dtype = self.o_dtype
|
||||
self.a_major = LayoutEnum.from_tensor(q).mma_major_mode()
|
||||
self.b_major = LayoutEnum.from_tensor(k).mma_major_mode()
|
||||
# FMHA-style V: reconstruct as (HEAD_DIM, s_k, 1) MN-major
|
||||
v_fmha = cute.make_tensor(
|
||||
v.iterator,
|
||||
cute.make_layout(
|
||||
(HEAD_DIM, 128, 1),
|
||||
stride=(1, HEAD_DIM, HEAD_DIM * 128),
|
||||
),
|
||||
)
|
||||
self.v_major = LayoutEnum.from_tensor(v_fmha).mma_major_mode()
|
||||
self.c_layout = LayoutEnum.from_tensor(c)
|
||||
qk_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, self.a_major, self.b_major, self.qk_acc_dtype, self.cta_group, (128,128), tcgen05.OperandSource.SMEM)
|
||||
pv_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, cute.nvgpu.OperandMajorMode.K, self.v_major, self.qk_acc_dtype, self.cta_group, (128,HEAD_DIM), tcgen05.OperandSource.TMEM)
|
||||
self._setup(qk_mma, pv_mma)
|
||||
q_s = cute.slice_(self.q_smem_s,(None,None,None,0)); k_s = cute.slice_(self.k_smem_s,(None,None,None,0)); v_s = cute.slice_(self.v_smem_s,(None,None,None,0))
|
||||
tma_q,mQ = cute.nvgpu.make_tiled_tma_atom_A(utils.sm100.cluster_shape_to_tma_atom_A(self.cluster_shape_mn,qk_mma.thr_id),q,q_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
|
||||
tma_k,mK = cute.nvgpu.make_tiled_tma_atom_B(utils.sm100.cluster_shape_to_tma_atom_B(self.cluster_shape_mn,qk_mma.thr_id),k,k_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
|
||||
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)
|
||||
self._kernel(qk_mma,pv_mma,tma_q,mQ,tma_k,mK,tma_v,mV,tma_c,mC,self.cluster_layout_vmnk,self.q_smem_s,self.k_smem_s,self.v_smem_s,self.p_tmem_s,self.c_smem_s,self.epi_tile).launch(grid=(1,1,1),block=[self.threads_per_cta,1,1],stream=stream)
|
||||
|
||||
@cute.kernel
|
||||
def _kernel(self, qk_mma, pv_mma, tma_q, mQ, tma_k, mK, tma_v, mV, tma_c, mC, cl_vmnk, q_smem_s, k_smem_s, v_smem_s, p_tmem_s, c_smem_s, epi_tile):
|
||||
warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
|
||||
tidx,_,_ = cute.arch.thread_idx()
|
||||
if warp_idx == self.tma_warp_id:
|
||||
cpasync.prefetch_descriptor(tma_q); cpasync.prefetch_descriptor(tma_k); cpasync.prefetch_descriptor(tma_v); cpasync.prefetch_descriptor(tma_c)
|
||||
|
||||
@cute.struct
|
||||
class SS:
|
||||
q_bar: cute.struct.MemRange[cutlass.Int64, self.q_stage*2]
|
||||
kv_bar: cute.struct.MemRange[cutlass.Int64, self.kv_stage*2]
|
||||
s_bar: cute.struct.MemRange[cutlass.Int64, 2]
|
||||
acc_bar: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage*2]
|
||||
tmem_dealloc: cutlass.Int64; holding: cutlass.Int32
|
||||
smem = utils.SmemAllocator(); st = smem.allocate(SS)
|
||||
|
||||
qp,qc = pipeline.PipelineTmaUmma.create(barrier_storage=st.q_bar.data_ptr(),num_stages=self.q_stage,producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread,1),tx_count=self.q_tx_bytes,cta_layout_vmnk=cl_vmnk,defer_sync=True).make_participants()
|
||||
kvp,kvc = pipeline.PipelineTmaUmma.create(barrier_storage=st.kv_bar.data_ptr(),num_stages=self.kv_stage,producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread,1),tx_count=self.kv_tx_bytes,cta_layout_vmnk=cl_vmnk,defer_sync=True).make_participants()
|
||||
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))
|
||||
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)))
|
||||
tmem = utils.TmemAllocator(st.holding.ptr,barrier_for_retrieve=tmem_bar,allocator_warp_id=self.epilogue_warp_id[0],is_two_cta=cute.size(qk_mma.thr_id.shape)==2,two_cta_tmem_dealloc_mbar_ptr=st.tmem_dealloc.ptr)
|
||||
pipeline.pipeline_init_arrive(cluster_shape_mn=cl_vmnk,is_relaxed=True)
|
||||
|
||||
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 = 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)
|
||||
|
||||
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))
|
||||
gC = cute.local_tile(mC,cute.slice_(self.pv_mma_tiler,(None,None,0)),(None,None,None))
|
||||
n_kv_tiles = cute.size(gK, mode=[3])
|
||||
|
||||
qk_thr = qk_mma.get_slice(0); pv_thr = pv_mma.get_slice(0)
|
||||
tCgQ = qk_thr.partition_A(gQ); tCgK = qk_thr.partition_B(gK)
|
||||
tCgV = pv_thr.partition_B(gV); tCgC = pv_thr.partition_C(gC)
|
||||
a_lay = cute.make_layout(cute.slice_(cl_vmnk,(0,0,None,0)).shape)
|
||||
tAsQ,tAgQ = cpasync.tma_partition(tma_q,0,a_lay,cute.group_modes(sQ,0,3),cute.group_modes(tCgQ,0,3))
|
||||
b_lay = cute.make_layout(cute.slice_(cl_vmnk,(0,None,0,0)).shape)
|
||||
tBsK,tBgK = cpasync.tma_partition(tma_k,0,b_lay,cute.group_modes(sK,0,3),cute.group_modes(tCgK,0,3))
|
||||
tVsV,tVgV = cpasync.tma_partition(tma_v,0,b_lay,cute.group_modes(sV,0,3),cute.group_modes(tCgV,0,3))
|
||||
tAgQ = tAgQ[(None,0,None,0)]; tBgK = tBgK[(None,0,None,0)]; tVgV = tVgV[(None,0,None,0)]
|
||||
|
||||
tCrQ = qk_mma.make_fragment_A(sQ); tCrK = qk_mma.make_fragment_B(sK)
|
||||
tCrV = pv_mma.make_fragment_B(sV)
|
||||
|
||||
qk_as = qk_thr.partition_shape_C(self.qk_mma_tiler[:2])
|
||||
tStS = qk_thr.make_fragment_C(qk_as)
|
||||
tStS0 = cute.make_tensor(tStS.iterator + self.tmem_s0_offset, tStS.layout)
|
||||
pv_as = pv_thr.partition_shape_C(self.pv_mma_tiler[:2])
|
||||
tOtO = pv_thr.make_fragment_C(pv_as)
|
||||
tOtO0 = cute.make_tensor(tOtO.iterator + self.tmem_o0_offset, tOtO.layout)
|
||||
|
||||
# --- PV read view (for MMA only, NOT for softmax store) ---
|
||||
tP = cute.make_tensor(tStS.iterator, p_tmem_s.outer)
|
||||
tOrP_base = pv_thr.make_fragment_A(tP)
|
||||
tOrP = tOrP_base[(None,None,None,0)]
|
||||
tOrP0 = cute.make_tensor(
|
||||
tOrP.iterator + self.qk_acc_dtype.width // self.q_dtype.width * self.tmem_p0_offset,
|
||||
tOrP.layout)
|
||||
|
||||
tCtS_fake = qk_mma.make_fragment_C(cute.append(qk_as, self.num_acc_stage))
|
||||
tCtO_fake = pv_mma.make_fragment_C(cute.append(pv_as, self.num_acc_stage))
|
||||
pipeline.pipeline_init_wait(cluster_shape_mn=cl_vmnk)
|
||||
|
||||
# TMA LOAD
|
||||
if warp_idx == self.tma_warp_id:
|
||||
qp.reset(); qh = qp.acquire_and_advance()
|
||||
cute.copy(tma_q,tAgQ[(None,qh.count)],tAsQ[(None,qh.index)],tma_bar_ptr=qh.barrier)
|
||||
qp.tail()
|
||||
kvp.reset(); pk = kvp.try_acquire()
|
||||
for kt in cutlass.range(n_kv_tiles,unroll=1):
|
||||
kh = kvp.acquire_and_advance(pk)
|
||||
cute.copy(tma_k,tBgK[(None,kh.count)],tBsK[(None,kh.index)],tma_bar_ptr=kh.barrier)
|
||||
pk = cutlass.Boolean(1)
|
||||
vh = kvp.acquire_and_advance(pk)
|
||||
cute.copy(tma_v,tVgV[(None,vh.count)],tVsV[(None,vh.index)],tma_bar_ptr=vh.barrier)
|
||||
pk = cutlass.Boolean(1)
|
||||
kvp.tail()
|
||||
|
||||
# MMA
|
||||
if warp_idx == self.mma_warp_id:
|
||||
tmem.wait_for_alloc()
|
||||
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)
|
||||
acc_pipe.producer_acquire(acc_st)
|
||||
for kt in range(n_kv_tiles):
|
||||
kh = kvc.wait_and_advance(pk); pk = cutlass.Boolean(1)
|
||||
sh = s_prod.acquire_and_advance()
|
||||
qk_mma.set(tcgen05.Field.ACCUMULATE, False)
|
||||
for kb in cutlass.range(cute.size(tCrQ,mode=[2]), unroll_full=True):
|
||||
cute.gemm(qk_mma, tStS0, tCrQ[(None,None,kb,0)], tCrK[(None,None,kb,kh.index)], tStS0)
|
||||
qk_mma.set(tcgen05.Field.ACCUMULATE, True)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
sh.commit(); kh.release()
|
||||
softmax_done_bar.arrive_and_wait()
|
||||
vh = kvc.wait_and_advance(pk); pk = cutlass.Boolean(1)
|
||||
pv_mma.set(tcgen05.Field.ACCUMULATE, kt != 0)
|
||||
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,vh.index)], tOtO0)
|
||||
pv_mma.set(tcgen05.Field.ACCUMULATE, True)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
vh.release()
|
||||
acc_pipe.producer_commit(acc_st); acc_st.advance()
|
||||
acc_pipe.producer_tail(acc_st)
|
||||
|
||||
# EPILOGUE
|
||||
if warp_idx < self.mma_warp_id:
|
||||
tmem.allocate(self.num_tmem_alloc_cols)
|
||||
tmem.wait_for_alloc()
|
||||
tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype)
|
||||
sfw_idx = tidx % (32 * len(self.epilogue_warp_id))
|
||||
|
||||
# --- S load (QK C-fragment layout) ---
|
||||
tmem_load_atom = cute.make_copy_atom(tcgen05.copy.Ld32x32bOp(tcgen05.copy.Repetition(32)), self.qk_acc_dtype)
|
||||
tiled_tmem_load = tcgen05.make_tmem_copy(tmem_load_atom, tStS0)
|
||||
thr_load = tiled_tmem_load.get_slice(sfw_idx)
|
||||
tTMEM_LOADtS = thr_load.partition_S(tStS0)
|
||||
|
||||
# S coordinate tensor (QK C-fragment)
|
||||
cS = cute.make_identity_tensor((self.qk_mma_tiler[0], self.qk_mma_tiler[1]))
|
||||
tScS = qk_thr.partition_C(cS)
|
||||
tTMEM_LOADcS = thr_load.partition_D(tScS)
|
||||
|
||||
# --- P store (QK C-fragment layout composition, FMHA pattern) ---
|
||||
# P logical columns = PV K = QK N = pv_mma_tiler[2]
|
||||
# Packed FP32 columns: BF16 pairs packed into FP32 words
|
||||
p_cols_fp32 = self.pv_mma_tiler[2] * self.q_dtype.width // self.qk_acc_dtype.width
|
||||
# BF16: 128 * 16 / 32 = 64
|
||||
|
||||
# P TMEM destination: QK C-fragment layout composed with P sub-tile
|
||||
tStP_layout = cute.composition(
|
||||
tStS.layout,
|
||||
cute.make_layout((self.pv_mma_tiler[0], p_cols_fp32)),
|
||||
)
|
||||
tStP0 = cute.make_tensor(
|
||||
tStS.iterator + self.tmem_p0_offset,
|
||||
tStP_layout,
|
||||
)
|
||||
|
||||
# P TMEM store atom and tiled copy
|
||||
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)
|
||||
thr_store = tiled_tmem_store.get_slice(sfw_idx)
|
||||
tTMEM_STOREtP = thr_store.partition_D(tStP0)
|
||||
|
||||
# P coordinate tensor: QK C-fragment coordinate composed with P sub-tile
|
||||
tScP_layout = cute.composition(
|
||||
tScS.layout,
|
||||
cute.make_layout((self.pv_mma_tiler[0], p_cols_fp32)),
|
||||
)
|
||||
tScP = cute.make_tensor(tScS.iterator, tScP_layout)
|
||||
tTMEM_STOREcP = thr_store.partition_S(tScP)
|
||||
|
||||
for kt in range(n_kv_tiles):
|
||||
si_handle = s_cons.wait_and_advance()
|
||||
|
||||
# Load S from TMEM (FP32, QK C-fragment layout)
|
||||
tTMEM_LOADrS = cute.make_rmem_tensor(tTMEM_LOADcS.shape, self.qk_acc_dtype)
|
||||
cute.copy(tiled_tmem_load, tTMEM_LOADtS, tTMEM_LOADrS)
|
||||
|
||||
# Register bridge (FMHA pattern):
|
||||
# rP_words: FP32 backing store with store-partition shape
|
||||
# rP_bf16: BF16 view over same registers using QK-load layout
|
||||
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,
|
||||
)
|
||||
|
||||
# Fragmented load→convert→store:
|
||||
# Load S as FP32, convert to BF16, store through rP_bf16 view
|
||||
frg_cnt = 4
|
||||
frg_tile = cute.size(tTMEM_LOADrS) // frg_cnt
|
||||
tTMEM_LOADrS_frg = cute.logical_divide(tTMEM_LOADrS, cute.make_layout(frg_tile))
|
||||
rP_bf16_frg = cute.logical_divide(rP_bf16, cute.make_layout(frg_tile))
|
||||
for j in range(frg_cnt):
|
||||
s_vec = tTMEM_LOADrS_frg[None, j].load()
|
||||
rP_bf16_frg[None, j].store(s_vec.to(self.q_dtype))
|
||||
|
||||
# Copy packed FP32 backing registers to TMEM
|
||||
cute.copy(tiled_tmem_store, rP_words, tTMEM_STOREtP)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
si_handle.release()
|
||||
softmax_done_bar.arrive()
|
||||
|
||||
tCtO_base = cute.make_tensor(tmem_ptr + self.tmem_o0_offset, tCtO_fake.layout)
|
||||
acc_cons_st = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, self.num_acc_stage)
|
||||
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 = utils.gemm.sm100.epilogue_tma_store(self, tidx, warp_idx, tma_c, tCtO_base, sC, tCgC, epi_tile, 0, const_expr(lambda x: x), (0,0,0), acc_cons_st, acc_pipe, c_pipe)
|
||||
c_pipe.producer_tail()
|
||||
tmem.relinquish_alloc_permit()
|
||||
tmem.free(tmem_ptr)
|
||||
|
||||
|
||||
def test():
|
||||
torch.manual_seed(42)
|
||||
for n in [128]:
|
||||
m, hd = 128, HEAD_DIM
|
||||
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 passed as (n, hd) row-major — FMHA-style reconstruction inside kernel
|
||||
v_kernel = v.unsqueeze(-1)
|
||||
c = torch.zeros(m, hd, 1, dtype=torch.bfloat16, device='cuda')
|
||||
qf = q[:,:,0].float(); kf = k[:,:,0].float()
|
||||
ref = (qf @ kf.T).bfloat16().float() @ v.float()
|
||||
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))
|
||||
stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
|
||||
kernel = FmhaV3()
|
||||
print(f'n={n}: Compiling...', flush=True)
|
||||
compiled = cute.compile(kernel, mQ, mK, mV, mC, stream)
|
||||
print(f'n={n}: tmem_offsets: s0={kernel.tmem_s0_offset} p0={kernel.tmem_p0_offset} o0={kernel.tmem_o0_offset} alloc={kernel.num_tmem_alloc_cols}', flush=True)
|
||||
print(f'n={n}: Running...', flush=True)
|
||||
compiled(mQ, mK, mV, mC, stream)
|
||||
torch.cuda.synchronize()
|
||||
out = c[:,:,0].float()
|
||||
cos = torch.nn.functional.cosine_similarity(out.flatten().unsqueeze(0), ref.flatten().unsqueeze(0)).item()
|
||||
print(f'FMHA v3 n={n} V=ones: cosine {cos:.6f} {"PASS" if cos >= 0.99 else "FAIL"}')
|
||||
if cos < 0.99:
|
||||
print(f' out[0,:4]={out[0,:4].tolist()} ref[0,:4]={ref[0,:4].tolist()}')
|
||||
|
||||
if __name__ == '__main__':
|
||||
test()
|
||||
327
tests/unit/test_fmha_v3_stage_c.py
Normal file
327
tests/unit/test_fmha_v3_stage_c.py
Normal file
@@ -0,0 +1,327 @@
|
||||
"""
|
||||
FMHA v3: QK -> softmax -> PV with KV-tile interleaving.
|
||||
Bug 4b fix (FMHA pattern): P store uses QK C-fragment layout composition,
|
||||
NOT PV A-fragment layout. Register bridge: FP32 backing (store partition shape)
|
||||
recast to BF16 view (QK-load layout).
|
||||
"""
|
||||
import torch, cutlass, cutlass.cute as cute, cutlass.utils as utils, cutlass.pipeline as pipeline
|
||||
from cutlass.cute.nvgpu import cpasync, tcgen05
|
||||
from cutlass import Float32, BFloat16, Int32, Boolean, const_expr
|
||||
from cutlass.utils import LayoutEnum
|
||||
from cutlass.utils.tmem_allocator import find_tmem_tensor_col_offset
|
||||
import cuda.bindings.driver as cuda
|
||||
import cutlass.torch as ct
|
||||
|
||||
HEAD_DIM = 64
|
||||
|
||||
class FmhaV3:
|
||||
def __init__(self):
|
||||
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; self.num_c_stage = 2
|
||||
self.kv_stage = 2; self.q_stage = 1; self.num_c_stage = 2
|
||||
|
||||
def _setup(self, qk_mma, pv_mma):
|
||||
qk_ik = cute.size(qk_mma.shape_mnk, mode=[2])
|
||||
self.qk_mma_tiler = (128, 128, qk_ik * 4)
|
||||
pv_ik = cute.size(pv_mma.shape_mnk, mode=[2])
|
||||
self.pv_mma_tiler = (128, HEAD_DIM, pv_ik * (128 // pv_ik))
|
||||
self.mma_tiler = self.qk_mma_tiler
|
||||
self.cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((1,1,1)), (qk_mma.thr_id.shape,))
|
||||
self.cta_tile_shape_mnk = (self.qk_mma_tiler[0]//cute.size(qk_mma.thr_id.shape), HEAD_DIM, self.qk_mma_tiler[2])
|
||||
self.c_layout = LayoutEnum.ROW_MAJOR
|
||||
self.epi_tile = utils.sm100.compute_epilogue_tile_shape(self.cta_tile_shape_mnk, False, self.c_layout, self.o_dtype)
|
||||
self.num_ab_stage = 1; self.num_acc_stage = 1
|
||||
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, 2)
|
||||
self.p_tmem_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)
|
||||
pv_thr = pv_mma.get_slice(0); pv_as = pv_thr.partition_shape_C(self.pv_mma_tiler[:2])
|
||||
tOtO = pv_thr.make_fragment_C(pv_as)
|
||||
self.tmem_s0_offset = 0; self.tmem_p0_offset = 32
|
||||
# P occupies [tmem_p0_offset, tmem_p0_offset + p_cols_fp32)
|
||||
# S occupies [0, qk_mma_tiler[1]) = [0, 128)
|
||||
# O must NOT overlap P. Place O after max(S end, P end), aligned to 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 # 32 + 64 = 96
|
||||
s_cols = self.qk_mma_tiler[1] # 128
|
||||
o_after = max(s_cols, p_end) # 128
|
||||
self.tmem_o0_offset = ((o_after + 31) // 32) * 32 # align to 32 = 128
|
||||
o_cols = find_tmem_tensor_col_offset(tOtO) # footprint of O
|
||||
total = self.tmem_o0_offset + o_cols
|
||||
# Must be multiple of 32 AND power of 2
|
||||
self.num_tmem_alloc_cols = 1
|
||||
while self.num_tmem_alloc_cols < total:
|
||||
self.num_tmem_alloc_cols *= 2
|
||||
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))
|
||||
self.q_tx_bytes = cute.size_in_bytes(self.q_dtype, q_s) * cta
|
||||
self.kv_tx_bytes = cute.size_in_bytes(self.q_dtype, k_s) * cta
|
||||
|
||||
@cute.jit
|
||||
def __call__(self, q, k, v, c, stream):
|
||||
self.q_dtype = q.element_type; self.o_dtype = c.element_type; self.c_dtype = self.o_dtype
|
||||
self.a_major = LayoutEnum.from_tensor(q).mma_major_mode()
|
||||
self.b_major = LayoutEnum.from_tensor(k).mma_major_mode()
|
||||
# FMHA-style V: reconstruct as (HEAD_DIM, s_k, 1) MN-major
|
||||
v_fmha = cute.make_tensor(
|
||||
v.iterator,
|
||||
cute.make_layout(
|
||||
(HEAD_DIM, 128, 1),
|
||||
stride=(1, HEAD_DIM, HEAD_DIM * 128),
|
||||
),
|
||||
)
|
||||
self.v_major = LayoutEnum.from_tensor(v_fmha).mma_major_mode()
|
||||
self.c_layout = LayoutEnum.from_tensor(c)
|
||||
qk_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, self.a_major, self.b_major, self.qk_acc_dtype, self.cta_group, (128,128), tcgen05.OperandSource.SMEM)
|
||||
pv_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, cute.nvgpu.OperandMajorMode.K, self.v_major, self.qk_acc_dtype, self.cta_group, (128,HEAD_DIM), tcgen05.OperandSource.TMEM)
|
||||
self._setup(qk_mma, pv_mma)
|
||||
q_s = cute.slice_(self.q_smem_s,(None,None,None,0)); k_s = cute.slice_(self.k_smem_s,(None,None,None,0)); v_s = cute.slice_(self.v_smem_s,(None,None,None,0))
|
||||
tma_q,mQ = cute.nvgpu.make_tiled_tma_atom_A(utils.sm100.cluster_shape_to_tma_atom_A(self.cluster_shape_mn,qk_mma.thr_id),q,q_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
|
||||
tma_k,mK = cute.nvgpu.make_tiled_tma_atom_B(utils.sm100.cluster_shape_to_tma_atom_B(self.cluster_shape_mn,qk_mma.thr_id),k,k_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
|
||||
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)
|
||||
self._kernel(qk_mma,pv_mma,tma_q,mQ,tma_k,mK,tma_v,mV,tma_c,mC,self.cluster_layout_vmnk,self.q_smem_s,self.k_smem_s,self.v_smem_s,self.p_tmem_s,self.c_smem_s,self.epi_tile).launch(grid=(1,1,1),block=[self.threads_per_cta,1,1],stream=stream)
|
||||
|
||||
@cute.kernel
|
||||
def _kernel(self, qk_mma, pv_mma, tma_q, mQ, tma_k, mK, tma_v, mV, tma_c, mC, cl_vmnk, q_smem_s, k_smem_s, v_smem_s, p_tmem_s, c_smem_s, epi_tile):
|
||||
warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
|
||||
tidx,_,_ = cute.arch.thread_idx()
|
||||
if warp_idx == self.tma_warp_id:
|
||||
cpasync.prefetch_descriptor(tma_q); cpasync.prefetch_descriptor(tma_k); cpasync.prefetch_descriptor(tma_v); cpasync.prefetch_descriptor(tma_c)
|
||||
|
||||
@cute.struct
|
||||
class SS:
|
||||
q_bar: cute.struct.MemRange[cutlass.Int64, self.q_stage*2]
|
||||
kv_bar: cute.struct.MemRange[cutlass.Int64, self.kv_stage*2]
|
||||
s_bar: cute.struct.MemRange[cutlass.Int64, 2]
|
||||
acc_bar: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage*2]
|
||||
tmem_dealloc: cutlass.Int64; holding: cutlass.Int32
|
||||
smem = utils.SmemAllocator(); st = smem.allocate(SS)
|
||||
|
||||
qp,qc = pipeline.PipelineTmaUmma.create(barrier_storage=st.q_bar.data_ptr(),num_stages=self.q_stage,producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread,1),tx_count=self.q_tx_bytes,cta_layout_vmnk=cl_vmnk,defer_sync=True).make_participants()
|
||||
kvp,kvc = pipeline.PipelineTmaUmma.create(barrier_storage=st.kv_bar.data_ptr(),num_stages=self.kv_stage,producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread,1),tx_count=self.kv_tx_bytes,cta_layout_vmnk=cl_vmnk,defer_sync=True).make_participants()
|
||||
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))
|
||||
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)))
|
||||
tmem = utils.TmemAllocator(st.holding.ptr,barrier_for_retrieve=tmem_bar,allocator_warp_id=self.epilogue_warp_id[0],is_two_cta=cute.size(qk_mma.thr_id.shape)==2,two_cta_tmem_dealloc_mbar_ptr=st.tmem_dealloc.ptr)
|
||||
pipeline.pipeline_init_arrive(cluster_shape_mn=cl_vmnk,is_relaxed=True)
|
||||
|
||||
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 = 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)
|
||||
|
||||
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))
|
||||
gC = cute.local_tile(mC,cute.slice_(self.pv_mma_tiler,(None,None,0)),(None,None,None))
|
||||
n_kv_tiles = cute.size(gK, mode=[3])
|
||||
|
||||
qk_thr = qk_mma.get_slice(0); pv_thr = pv_mma.get_slice(0)
|
||||
tCgQ = qk_thr.partition_A(gQ); tCgK = qk_thr.partition_B(gK)
|
||||
tCgV = pv_thr.partition_B(gV); tCgC = pv_thr.partition_C(gC)
|
||||
a_lay = cute.make_layout(cute.slice_(cl_vmnk,(0,0,None,0)).shape)
|
||||
tAsQ,tAgQ = cpasync.tma_partition(tma_q,0,a_lay,cute.group_modes(sQ,0,3),cute.group_modes(tCgQ,0,3))
|
||||
b_lay = cute.make_layout(cute.slice_(cl_vmnk,(0,None,0,0)).shape)
|
||||
tBsK,tBgK = cpasync.tma_partition(tma_k,0,b_lay,cute.group_modes(sK,0,3),cute.group_modes(tCgK,0,3))
|
||||
tVsV,tVgV = cpasync.tma_partition(tma_v,0,b_lay,cute.group_modes(sV,0,3),cute.group_modes(tCgV,0,3))
|
||||
tAgQ = tAgQ[(None,0,None,0)]; tBgK = tBgK[(None,0,None,0)]; tVgV = tVgV[(None,0,None,0)]
|
||||
|
||||
tCrQ = qk_mma.make_fragment_A(sQ); tCrK = qk_mma.make_fragment_B(sK)
|
||||
tCrV = pv_mma.make_fragment_B(sV)
|
||||
|
||||
qk_as = qk_thr.partition_shape_C(self.qk_mma_tiler[:2])
|
||||
tStS = qk_thr.make_fragment_C(qk_as)
|
||||
tStS0 = cute.make_tensor(tStS.iterator + self.tmem_s0_offset, tStS.layout)
|
||||
pv_as = pv_thr.partition_shape_C(self.pv_mma_tiler[:2])
|
||||
tOtO = pv_thr.make_fragment_C(pv_as)
|
||||
tOtO0 = cute.make_tensor(tOtO.iterator + self.tmem_o0_offset, tOtO.layout)
|
||||
|
||||
# --- PV read view (for MMA only, NOT for softmax store) ---
|
||||
tP = cute.make_tensor(tStS.iterator, p_tmem_s.outer)
|
||||
tOrP_base = pv_thr.make_fragment_A(tP)
|
||||
tOrP = tOrP_base[(None,None,None,0)]
|
||||
tOrP0 = cute.make_tensor(
|
||||
tOrP.iterator + self.qk_acc_dtype.width // self.q_dtype.width * self.tmem_p0_offset,
|
||||
tOrP.layout)
|
||||
|
||||
tCtS_fake = qk_mma.make_fragment_C(cute.append(qk_as, self.num_acc_stage))
|
||||
tCtO_fake = pv_mma.make_fragment_C(cute.append(pv_as, self.num_acc_stage))
|
||||
pipeline.pipeline_init_wait(cluster_shape_mn=cl_vmnk)
|
||||
|
||||
# TMA LOAD
|
||||
if warp_idx == self.tma_warp_id:
|
||||
qp.reset(); qh = qp.acquire_and_advance()
|
||||
cute.copy(tma_q,tAgQ[(None,qh.count)],tAsQ[(None,qh.index)],tma_bar_ptr=qh.barrier)
|
||||
qp.tail()
|
||||
kvp.reset(); pk = kvp.try_acquire()
|
||||
for kt in cutlass.range(n_kv_tiles,unroll=1):
|
||||
kh = kvp.acquire_and_advance(pk)
|
||||
cute.copy(tma_k,tBgK[(None,kh.count)],tBsK[(None,kh.index)],tma_bar_ptr=kh.barrier)
|
||||
pk = cutlass.Boolean(1)
|
||||
vh = kvp.acquire_and_advance(pk)
|
||||
cute.copy(tma_v,tVgV[(None,vh.count)],tVsV[(None,vh.index)],tma_bar_ptr=vh.barrier)
|
||||
pk = cutlass.Boolean(1)
|
||||
kvp.tail()
|
||||
|
||||
# MMA
|
||||
if warp_idx == self.mma_warp_id:
|
||||
tmem.wait_for_alloc()
|
||||
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)
|
||||
acc_pipe.producer_acquire(acc_st)
|
||||
for kt in range(n_kv_tiles):
|
||||
kh = kvc.wait_and_advance(pk); pk = cutlass.Boolean(1)
|
||||
sh = s_prod.acquire_and_advance()
|
||||
qk_mma.set(tcgen05.Field.ACCUMULATE, False)
|
||||
for kb in cutlass.range(cute.size(tCrQ,mode=[2]), unroll_full=True):
|
||||
cute.gemm(qk_mma, tStS0, tCrQ[(None,None,kb,0)], tCrK[(None,None,kb,kh.index)], tStS0)
|
||||
qk_mma.set(tcgen05.Field.ACCUMULATE, True)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
sh.commit(); kh.release()
|
||||
softmax_done_bar.arrive_and_wait()
|
||||
vh = kvc.wait_and_advance(pk); pk = cutlass.Boolean(1)
|
||||
pv_mma.set(tcgen05.Field.ACCUMULATE, kt != 0)
|
||||
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,vh.index)], tOtO0)
|
||||
pv_mma.set(tcgen05.Field.ACCUMULATE, True)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
vh.release()
|
||||
acc_pipe.producer_commit(acc_st); acc_st.advance()
|
||||
acc_pipe.producer_tail(acc_st)
|
||||
|
||||
# EPILOGUE
|
||||
if warp_idx < self.mma_warp_id:
|
||||
tmem.allocate(self.num_tmem_alloc_cols)
|
||||
tmem.wait_for_alloc()
|
||||
tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype)
|
||||
sfw_idx = tidx % (32 * len(self.epilogue_warp_id))
|
||||
|
||||
# --- S load (QK C-fragment layout) ---
|
||||
tmem_load_atom = cute.make_copy_atom(tcgen05.copy.Ld32x32bOp(tcgen05.copy.Repetition(32)), self.qk_acc_dtype)
|
||||
tiled_tmem_load = tcgen05.make_tmem_copy(tmem_load_atom, tStS0)
|
||||
thr_load = tiled_tmem_load.get_slice(sfw_idx)
|
||||
tTMEM_LOADtS = thr_load.partition_S(tStS0)
|
||||
|
||||
# S coordinate tensor (QK C-fragment)
|
||||
cS = cute.make_identity_tensor((self.qk_mma_tiler[0], self.qk_mma_tiler[1]))
|
||||
tScS = qk_thr.partition_C(cS)
|
||||
tTMEM_LOADcS = thr_load.partition_D(tScS)
|
||||
|
||||
# --- P store (QK C-fragment layout composition, FMHA pattern) ---
|
||||
# P logical columns = PV K = QK N = pv_mma_tiler[2]
|
||||
# Packed FP32 columns: BF16 pairs packed into FP32 words
|
||||
p_cols_fp32 = self.pv_mma_tiler[2] * self.q_dtype.width // self.qk_acc_dtype.width
|
||||
# BF16: 128 * 16 / 32 = 64
|
||||
|
||||
# P TMEM destination: QK C-fragment layout composed with P sub-tile
|
||||
tStP_layout = cute.composition(
|
||||
tStS.layout,
|
||||
cute.make_layout((self.pv_mma_tiler[0], p_cols_fp32)),
|
||||
)
|
||||
tStP0 = cute.make_tensor(
|
||||
tStS.iterator + self.tmem_p0_offset,
|
||||
tStP_layout,
|
||||
)
|
||||
|
||||
# P TMEM store atom and tiled copy
|
||||
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)
|
||||
thr_store = tiled_tmem_store.get_slice(sfw_idx)
|
||||
tTMEM_STOREtP = thr_store.partition_D(tStP0)
|
||||
|
||||
# P coordinate tensor: QK C-fragment coordinate composed with P sub-tile
|
||||
tScP_layout = cute.composition(
|
||||
tScS.layout,
|
||||
cute.make_layout((self.pv_mma_tiler[0], p_cols_fp32)),
|
||||
)
|
||||
tScP = cute.make_tensor(tScS.iterator, tScP_layout)
|
||||
tTMEM_STOREcP = thr_store.partition_S(tScP)
|
||||
|
||||
for kt in range(n_kv_tiles):
|
||||
si_handle = s_cons.wait_and_advance()
|
||||
|
||||
# Load S from TMEM (FP32, QK C-fragment layout)
|
||||
tTMEM_LOADrS = cute.make_rmem_tensor(tTMEM_LOADcS.shape, self.qk_acc_dtype)
|
||||
cute.copy(tiled_tmem_load, tTMEM_LOADtS, tTMEM_LOADrS)
|
||||
|
||||
# Register bridge (FMHA pattern):
|
||||
# rP_words: FP32 backing store with store-partition shape
|
||||
# rP_bf16: BF16 view over same registers using QK-load layout
|
||||
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,
|
||||
)
|
||||
|
||||
# Fragmented load→convert→store:
|
||||
# Load S as FP32, convert to BF16, store through rP_bf16 view
|
||||
frg_cnt = 4
|
||||
frg_tile = cute.size(tTMEM_LOADrS) // frg_cnt
|
||||
tTMEM_LOADrS_frg = cute.logical_divide(tTMEM_LOADrS, cute.make_layout(frg_tile))
|
||||
rP_bf16_frg = cute.logical_divide(rP_bf16, cute.make_layout(frg_tile))
|
||||
for j in range(frg_cnt):
|
||||
s_vec = tTMEM_LOADrS_frg[None, j].load()
|
||||
rP_bf16_frg[None, j].store(s_vec.to(self.q_dtype))
|
||||
|
||||
# Copy packed FP32 backing registers to TMEM
|
||||
cute.copy(tiled_tmem_store, rP_words, tTMEM_STOREtP)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
si_handle.release()
|
||||
softmax_done_bar.arrive()
|
||||
|
||||
tCtO_base = cute.make_tensor(tmem_ptr + self.tmem_o0_offset, tCtO_fake.layout)
|
||||
acc_cons_st = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, self.num_acc_stage)
|
||||
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 = utils.gemm.sm100.epilogue_tma_store(self, tidx, warp_idx, tma_c, tCtO_base, sC, tCgC, epi_tile, 0, const_expr(lambda x: x), (0,0,0), acc_cons_st, acc_pipe, c_pipe)
|
||||
c_pipe.producer_tail()
|
||||
tmem.relinquish_alloc_permit()
|
||||
tmem.free(tmem_ptr)
|
||||
|
||||
|
||||
def test():
|
||||
torch.manual_seed(42)
|
||||
for n in [128]:
|
||||
m, hd = 128, HEAD_DIM
|
||||
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 passed as (n, hd) row-major — FMHA-style reconstruction inside kernel
|
||||
v_kernel = v.unsqueeze(-1)
|
||||
c = torch.zeros(m, hd, 1, dtype=torch.bfloat16, device='cuda')
|
||||
qf = q[:,:,0].float(); kf = k[:,:,0].float()
|
||||
ref = (qf @ kf.T).bfloat16().float() @ v.float()
|
||||
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))
|
||||
stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
|
||||
kernel = FmhaV3()
|
||||
print(f'n={n}: Compiling...', flush=True)
|
||||
compiled = cute.compile(kernel, mQ, mK, mV, mC, stream)
|
||||
print(f'n={n}: tmem_offsets: s0={kernel.tmem_s0_offset} p0={kernel.tmem_p0_offset} o0={kernel.tmem_o0_offset} alloc={kernel.num_tmem_alloc_cols}', flush=True)
|
||||
print(f'n={n}: Running...', flush=True)
|
||||
compiled(mQ, mK, mV, mC, stream)
|
||||
torch.cuda.synchronize()
|
||||
out = c[:,:,0].float()
|
||||
cos = torch.nn.functional.cosine_similarity(out.flatten().unsqueeze(0), ref.flatten().unsqueeze(0)).item()
|
||||
print(f'FMHA v3 n={n} V=ones: cosine {cos:.6f} {"PASS" if cos >= 0.99 else "FAIL"}')
|
||||
if cos < 0.99:
|
||||
print(f' out[0,:4]={out[0,:4].tolist()} ref[0,:4]={ref[0,:4].tolist()}')
|
||||
|
||||
if __name__ == '__main__':
|
||||
test()
|
||||
305
tests/unit/test_fmha_v3_stage_c_min.py
Normal file
305
tests/unit/test_fmha_v3_stage_c_min.py
Normal file
@@ -0,0 +1,305 @@
|
||||
"""
|
||||
FMHA v3 Stage-C minimal: 12-warps, identity softmax, identity correction.
|
||||
Validates pipeline chain: mma_s, s_corr, mma_corr, corr_epi.
|
||||
"""
|
||||
import torch, cutlass, cutlass.cute as cute, cutlass.utils as utils, cutlass.pipeline as pipeline
|
||||
from cutlass.cute.nvgpu import cpasync, tcgen05
|
||||
from cutlass import Float32, BFloat16, Int32, Boolean, const_expr
|
||||
from cutlass.utils import LayoutEnum
|
||||
from cutlass.utils.tmem_allocator import find_tmem_tensor_col_offset
|
||||
import cuda.bindings.driver as cuda
|
||||
import cutlass.torch as ct
|
||||
|
||||
HEAD_DIM = 64
|
||||
|
||||
class FmhaV3StageCMin:
|
||||
def __init__(self, s_k=128):
|
||||
self.s_k = s_k
|
||||
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.softmax_warp_ids = (0,1,2,3)
|
||||
self.correction_warp_ids = (4,5,6,7)
|
||||
self.mma_warp_id = 8; self.tma_warp_id = 9
|
||||
self.epilogue_warp_id = (10,)
|
||||
self.epi_warp_id = 10; self.empty_warp_id = 11
|
||||
self.threads_per_cta = 32 * 12
|
||||
self.mma_softmax_stage = 1; self.softmax_corr_stage = 1
|
||||
self.mma_corr_stage = 2; self.epi_stage = 2
|
||||
self.kv_stage = 2; self.q_stage = 1; self.num_c_stage = 2
|
||||
|
||||
def _setup(self, qk_mma, pv_mma):
|
||||
qk_ik = cute.size(qk_mma.shape_mnk, mode=[2])
|
||||
self.qk_mma_tiler = (128, 128, qk_ik * 4)
|
||||
pv_ik = cute.size(pv_mma.shape_mnk, mode=[2])
|
||||
self.pv_mma_tiler = (128, HEAD_DIM, pv_ik * (128 // pv_ik))
|
||||
self.mma_tiler = self.qk_mma_tiler
|
||||
self.cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((1,1,1)), (qk_mma.thr_id.shape,))
|
||||
self.cta_tile_shape_mnk = (self.qk_mma_tiler[0]//cute.size(qk_mma.thr_id.shape), HEAD_DIM, self.qk_mma_tiler[2])
|
||||
self.c_layout = LayoutEnum.ROW_MAJOR
|
||||
self.epi_tile = utils.sm100.compute_epilogue_tile_shape(self.cta_tile_shape_mnk, False, self.c_layout, self.o_dtype)
|
||||
self.num_ab_stage = 1; self.num_acc_stage = 1
|
||||
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, 2)
|
||||
self.p_tmem_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)
|
||||
pv_thr = pv_mma.get_slice(0); pv_as = pv_thr.partition_shape_C(self.pv_mma_tiler[:2])
|
||||
tOtO = pv_thr.make_fragment_C(pv_as)
|
||||
self.tmem_s0_offset = 0; 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
|
||||
s_cols = self.qk_mma_tiler[1]; o_after = max(s_cols, p_end)
|
||||
self.tmem_o0_offset = ((o_after + 31) // 32) * 32
|
||||
o_cols = find_tmem_tensor_col_offset(tOtO)
|
||||
total = self.tmem_o0_offset + o_cols
|
||||
self.num_tmem_alloc_cols = 1
|
||||
while self.num_tmem_alloc_cols < total:
|
||||
self.num_tmem_alloc_cols *= 2
|
||||
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))
|
||||
self.q_tx_bytes = cute.size_in_bytes(self.q_dtype, q_s) * cta
|
||||
self.kv_tx_bytes = cute.size_in_bytes(self.q_dtype, k_s) * cta
|
||||
|
||||
@cute.jit
|
||||
def __call__(self, q, k, v, c, stream):
|
||||
self.q_dtype = q.element_type; self.o_dtype = c.element_type; self.c_dtype = self.o_dtype
|
||||
self.a_major = LayoutEnum.from_tensor(q).mma_major_mode()
|
||||
self.b_major = LayoutEnum.from_tensor(k).mma_major_mode()
|
||||
v_fmha = cute.make_tensor(v.iterator, cute.make_layout((HEAD_DIM, self.s_k, 1), stride=(1, HEAD_DIM, HEAD_DIM * self.s_k)))
|
||||
self.v_major = LayoutEnum.from_tensor(v_fmha).mma_major_mode()
|
||||
self.c_layout = LayoutEnum.from_tensor(c)
|
||||
qk_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, self.a_major, self.b_major, self.qk_acc_dtype, self.cta_group, (128,128), tcgen05.OperandSource.SMEM)
|
||||
pv_mma = utils.sm100.make_trivial_tiled_mma(self.q_dtype, self.q_dtype, cute.nvgpu.OperandMajorMode.K, self.v_major, self.qk_acc_dtype, self.cta_group, (128,HEAD_DIM), tcgen05.OperandSource.TMEM)
|
||||
self._setup(qk_mma, pv_mma)
|
||||
q_s = cute.slice_(self.q_smem_s,(None,None,None,0)); k_s = cute.slice_(self.k_smem_s,(None,None,None,0)); v_s = cute.slice_(self.v_smem_s,(None,None,None,0))
|
||||
tma_q,mQ = cute.nvgpu.make_tiled_tma_atom_A(utils.sm100.cluster_shape_to_tma_atom_A(self.cluster_shape_mn,qk_mma.thr_id),q,q_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
|
||||
tma_k,mK = cute.nvgpu.make_tiled_tma_atom_B(utils.sm100.cluster_shape_to_tma_atom_B(self.cluster_shape_mn,qk_mma.thr_id),k,k_s,self.qk_mma_tiler,qk_mma,self.cluster_layout_vmnk.shape)
|
||||
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)
|
||||
self._kernel(qk_mma,pv_mma,tma_q,mQ,tma_k,mK,tma_v,mV,tma_c,mC,self.cluster_layout_vmnk,self.q_smem_s,self.k_smem_s,self.v_smem_s,self.p_tmem_s,self.c_smem_s,self.epi_tile).launch(grid=(1,1,1),block=[self.threads_per_cta,1,1],stream=stream)
|
||||
|
||||
@cute.kernel
|
||||
def _kernel(self, qk_mma, pv_mma, tma_q, mQ, tma_k, mK, tma_v, mV, tma_c, mC, cl_vmnk, q_smem_s, k_smem_s, v_smem_s, p_tmem_s, c_smem_s, epi_tile):
|
||||
warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
|
||||
tidx,_,_ = cute.arch.thread_idx()
|
||||
if warp_idx == self.tma_warp_id:
|
||||
cpasync.prefetch_descriptor(tma_q); cpasync.prefetch_descriptor(tma_k); cpasync.prefetch_descriptor(tma_v); cpasync.prefetch_descriptor(tma_c)
|
||||
@cute.struct
|
||||
class SS:
|
||||
q_bar: cute.struct.MemRange[cutlass.Int64, self.q_stage*2]
|
||||
kv_bar: cute.struct.MemRange[cutlass.Int64, self.kv_stage*2]
|
||||
mma_s_bar: cute.struct.MemRange[cutlass.Int64, self.mma_softmax_stage*2]
|
||||
s_corr_bar: cute.struct.MemRange[cutlass.Int64, self.softmax_corr_stage*2]
|
||||
mma_corr_bar: cute.struct.MemRange[cutlass.Int64, self.mma_corr_stage*2]
|
||||
corr_epi_bar: cute.struct.MemRange[cutlass.Int64, self.epi_stage*2]
|
||||
tmem_dealloc: cutlass.Int64
|
||||
holding: cutlass.Int32
|
||||
smem = utils.SmemAllocator(); st = smem.allocate(SS)
|
||||
def cg(n): return pipeline.CooperativeGroup(pipeline.Agent.Thread, n)
|
||||
qp,qc = pipeline.PipelineTmaUmma.create(barrier_storage=st.q_bar.data_ptr(),num_stages=self.q_stage,producer_group=cg(1),consumer_group=cg(1),tx_count=self.q_tx_bytes,cta_layout_vmnk=cl_vmnk,defer_sync=True).make_participants()
|
||||
kvp,kvc = pipeline.PipelineTmaUmma.create(barrier_storage=st.kv_bar.data_ptr(),num_stages=self.kv_stage,producer_group=cg(1),consumer_group=cg(1),tx_count=self.kv_tx_bytes,cta_layout_vmnk=cl_vmnk,defer_sync=True).make_participants()
|
||||
mma_s_prod,mma_s_cons = pipeline.PipelineUmmaAsync.create(barrier_storage=st.mma_s_bar.data_ptr(),num_stages=self.mma_softmax_stage,producer_group=cg(1),consumer_group=cg(32*len(self.softmax_warp_ids)),cta_layout_vmnk=cl_vmnk,defer_sync=True).make_participants()
|
||||
s_corr_prod,s_corr_cons = pipeline.PipelineAsync.create(barrier_storage=st.s_corr_bar.data_ptr(),num_stages=self.softmax_corr_stage,producer_group=cg(32*len(self.softmax_warp_ids)),consumer_group=cg(32*len(self.correction_warp_ids))).make_participants()
|
||||
mma_corr_pipe = pipeline.PipelineUmmaAsync.create(barrier_storage=st.mma_corr_bar.data_ptr(),num_stages=self.mma_corr_stage,producer_group=cg(1),consumer_group=cg(32*len(self.correction_warp_ids)),cta_layout_vmnk=cl_vmnk,defer_sync=True)
|
||||
corr_epi_prod,corr_epi_cons = pipeline.PipelineAsync.create(barrier_storage=st.corr_epi_bar.data_ptr(),num_stages=self.epi_stage,producer_group=cg(32*len(self.correction_warp_ids)),consumer_group=cg(32)).make_participants()
|
||||
tmem_bar = pipeline.NamedBarrier(barrier_id=2,num_threads=32*len((*self.softmax_warp_ids,*self.correction_warp_ids,self.mma_warp_id)))
|
||||
tmem = utils.TmemAllocator(st.holding.ptr,barrier_for_retrieve=tmem_bar,allocator_warp_id=self.softmax_warp_ids[0],is_two_cta=cute.size(qk_mma.thr_id.shape)==2,two_cta_tmem_dealloc_mbar_ptr=st.tmem_dealloc)
|
||||
if warp_idx == self.empty_warp_id:
|
||||
cute.arch.mbarrier_init(st.tmem_dealloc, 32*len((*self.softmax_warp_ids,*self.correction_warp_ids)))
|
||||
cute.arch.mbarrier_init_fence()
|
||||
pipeline.pipeline_init_arrive(cluster_shape_mn=cl_vmnk,is_relaxed=True)
|
||||
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 = 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)
|
||||
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))
|
||||
gC = cute.local_tile(mC,cute.slice_(self.pv_mma_tiler,(None,None,0)),(None,None,None))
|
||||
n_kv_tiles = cute.size(gK, mode=[3])
|
||||
qk_thr = qk_mma.get_slice(0); pv_thr = pv_mma.get_slice(0)
|
||||
tCgQ = qk_thr.partition_A(gQ); tCgK = qk_thr.partition_B(gK)
|
||||
tCgV = pv_thr.partition_B(gV); tCgC = pv_thr.partition_C(gC)
|
||||
a_lay = cute.make_layout(cute.slice_(cl_vmnk,(0,0,None,0)).shape)
|
||||
tAsQ,tAgQ = cpasync.tma_partition(tma_q,0,a_lay,cute.group_modes(sQ,0,3),cute.group_modes(tCgQ,0,3))
|
||||
b_lay = cute.make_layout(cute.slice_(cl_vmnk,(0,None,0,0)).shape)
|
||||
tBsK,tBgK = cpasync.tma_partition(tma_k,0,b_lay,cute.group_modes(sK,0,3),cute.group_modes(tCgK,0,3))
|
||||
tVsV,tVgV = cpasync.tma_partition(tma_v,0,b_lay,cute.group_modes(sV,0,3),cute.group_modes(tCgV,0,3))
|
||||
tAgQ = tAgQ[(None,0,None,0)]; tBgK = tBgK[(None,0,None,0)]; tVgV = tVgV[(None,0,None,0)]
|
||||
tCrQ = qk_mma.make_fragment_A(sQ); tCrK = qk_mma.make_fragment_B(sK)
|
||||
tCrV = pv_mma.make_fragment_B(sV)
|
||||
qk_as = qk_thr.partition_shape_C(self.qk_mma_tiler[:2])
|
||||
tStS = qk_thr.make_fragment_C(qk_as)
|
||||
tStS0 = cute.make_tensor(tStS.iterator + self.tmem_s0_offset, tStS.layout)
|
||||
pv_as = pv_thr.partition_shape_C(self.pv_mma_tiler[:2])
|
||||
tOtO = pv_thr.make_fragment_C(pv_as)
|
||||
tOtO0 = cute.make_tensor(tOtO.iterator + self.tmem_o0_offset, tOtO.layout)
|
||||
tP = cute.make_tensor(tStS.iterator, p_tmem_s.outer)
|
||||
tOrP_base = pv_thr.make_fragment_A(tP)
|
||||
tOrP = tOrP_base[(None,None,None,0)]
|
||||
tOrP0 = cute.make_tensor(tOrP.iterator + self.qk_acc_dtype.width // self.q_dtype.width * self.tmem_p0_offset, tOrP.layout)
|
||||
tCtO_fake = pv_mma.make_fragment_C(cute.append(pv_as, 1))
|
||||
pipeline.pipeline_init_wait(cluster_shape_mn=cl_vmnk)
|
||||
|
||||
# ==================== TMA WARP (9) ====================
|
||||
if warp_idx == self.tma_warp_id:
|
||||
qp.reset(); qh = qp.acquire_and_advance()
|
||||
cute.copy(tma_q,tAgQ[(None,qh.count)],tAsQ[(None,qh.index)],tma_bar_ptr=qh.barrier)
|
||||
qp.tail()
|
||||
kvp.reset(); pk = kvp.try_acquire()
|
||||
for kt in cutlass.range(n_kv_tiles,unroll=1):
|
||||
kh = kvp.acquire_and_advance(pk)
|
||||
cute.copy(tma_k,tBgK[(None,kh.count)],tBsK[(None,kh.index)],tma_bar_ptr=kh.barrier)
|
||||
pk = cutlass.Boolean(1)
|
||||
vh = kvp.acquire_and_advance(pk)
|
||||
cute.copy(tma_v,tVgV[(None,vh.count)],tVsV[(None,vh.index)],tma_bar_ptr=vh.barrier)
|
||||
pk = cutlass.Boolean(1)
|
||||
kvp.tail()
|
||||
|
||||
# ==================== MMA WARP (8) ====================
|
||||
if warp_idx == self.mma_warp_id:
|
||||
tmem.wait_for_alloc()
|
||||
qc.reset(); qh = qc.wait_and_advance(); qh.release()
|
||||
kvc.reset(); pk = kvc.try_wait()
|
||||
for kt in range(n_kv_tiles):
|
||||
kh = kvc.wait_and_advance(pk); pk = cutlass.Boolean(1)
|
||||
sh = mma_s_prod.acquire_and_advance()
|
||||
qk_mma.set(tcgen05.Field.ACCUMULATE, False)
|
||||
for kb in cutlass.range(cute.size(tCrQ,mode=[2]), unroll_full=True):
|
||||
cute.gemm(qk_mma, tStS0, tCrQ[(None,None,kb,0)], tCrK[(None,None,kb,kh.index)], tStS0)
|
||||
qk_mma.set(tcgen05.Field.ACCUMULATE, True)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
sh.commit(); kh.release()
|
||||
# MMA waits for softmax to produce P (softmax consumes S, releases when P ready)
|
||||
# In the pipeline model, the S release by softmax IS the P-ready signal
|
||||
# But with PipelineUmmaAsync, the consumer release releases the producer handle
|
||||
# So after the softmax releases, the MMA can acquire the next S handle
|
||||
|
||||
vh = kvc.wait_and_advance(pk); pk = cutlass.Boolean(1)
|
||||
oh = mma_corr_pipe.producer_acquire(pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, self.mma_corr_stage))
|
||||
pv_mma.set(tcgen05.Field.ACCUMULATE, kt != 0)
|
||||
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,vh.index)], tOtO0)
|
||||
pv_mma.set(tcgen05.Field.ACCUMULATE, True)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
oh.commit(); vh.release()
|
||||
mma_s_prod.tail()
|
||||
mma_corr_prod.tail()
|
||||
cute.arch.relinquish_tmem_alloc_permit()
|
||||
cute.arch.mbarrier_wait(st.tmem_dealloc, 0)
|
||||
tmem_ptr = cute.arch.retrieve_tmem_ptr(self.qk_acc_dtype, alignment=16, ptr_to_buffer_holding_addr=st.holding)
|
||||
cute.arch.dealloc_tmem(tmem_ptr, Int32(self.num_tmem_alloc_cols))
|
||||
|
||||
# ==================== SOFTMAX WARPS (0-3) — identity ====================
|
||||
if warp_idx < len(self.softmax_warp_ids):
|
||||
tmem.allocate(self.num_tmem_alloc_cols)
|
||||
tmem.wait_for_alloc()
|
||||
sfw_idx = tidx % (32 * len(self.softmax_warp_ids))
|
||||
tmem_load_atom = cute.make_copy_atom(tcgen05.copy.Ld32x32bOp(tcgen05.copy.Repetition(32)), self.qk_acc_dtype)
|
||||
tiled_tmem_load = tcgen05.make_tmem_copy(tmem_load_atom, tStS0)
|
||||
thr_load = tiled_tmem_load.get_slice(sfw_idx)
|
||||
tTMEM_LOADtS = thr_load.partition_S(tStS0)
|
||||
cS = cute.make_identity_tensor((self.qk_mma_tiler[0], self.qk_mma_tiler[1]))
|
||||
tScS = qk_thr.partition_C(cS)
|
||||
tTMEM_LOADcS = thr_load.partition_D(tScS)
|
||||
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)))
|
||||
tStP0 = cute.make_tensor(tStS.iterator + self.tmem_p0_offset, 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)
|
||||
thr_store = tiled_tmem_store.get_slice(sfw_idx)
|
||||
tTMEM_STOREtP = thr_store.partition_D(tStP0)
|
||||
tScP_layout = cute.composition(tScS.layout, cute.make_layout((self.pv_mma_tiler[0], p_cols_fp32)))
|
||||
tTMEM_STOREcP = thr_store.partition_S(cute.make_tensor(tScS.iterator, tScP_layout))
|
||||
vec_handle = s_corr_prod.acquire_and_advance()
|
||||
for kt in range(n_kv_tiles):
|
||||
si_handle = mma_s_cons.wait_and_advance()
|
||||
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()
|
||||
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)
|
||||
frg_cnt = 4
|
||||
frg_tile = cute.size(tTMEM_LOADrS) // frg_cnt
|
||||
tTMEM_LOADrS_frg = cute.logical_divide(tTMEM_LOADrS, cute.make_layout(frg_tile))
|
||||
rP_bf16_frg = cute.logical_divide(rP_bf16, cute.make_layout(frg_tile))
|
||||
for j in range(frg_cnt):
|
||||
s_vec = tTMEM_LOADrS_frg[None, j].load()
|
||||
rP_bf16_frg[None, j].store(s_vec.to(self.q_dtype))
|
||||
cute.copy(tiled_tmem_store, rP_words, tTMEM_STOREtP)
|
||||
cute.arch.fence_view_async_tmem_store()
|
||||
vec_handle.commit()
|
||||
si_handle.release()
|
||||
vec_handle = s_corr_prod.acquire_and_advance()
|
||||
s_corr_prod.tail()
|
||||
cute.arch.mbarrier_arrive(st.tmem_dealloc)
|
||||
tmem.relinquish_alloc_permit()
|
||||
|
||||
# ==================== CORRECTION WARPS (4-7) — identity, no epilogue ====================
|
||||
if warp_idx >= len(self.softmax_warp_ids) and warp_idx < len(self.softmax_warp_ids) + len(self.correction_warp_ids):
|
||||
tmem.wait_for_alloc()
|
||||
corr_idx = tidx % (32 * len(self.correction_warp_ids))
|
||||
first_vec = s_corr_cons.wait_and_advance()
|
||||
first_vec.release()
|
||||
for kt in range(n_kv_tiles - 1):
|
||||
vec = s_corr_cons.wait_and_advance()
|
||||
o = mma_corr_cons.wait_and_advance()
|
||||
o.release()
|
||||
vec.release()
|
||||
final_vec = s_corr_cons.wait_and_advance()
|
||||
final_vec.release()
|
||||
final_o = mma_corr_cons.wait_and_advance()
|
||||
# Write O from TMEM to output using the epilogue pipeline
|
||||
epi_handle = corr_epi_prod.acquire_and_advance()
|
||||
tmem_ptr = tmem.retrieve_ptr(self.qk_acc_dtype)
|
||||
tCtO_base = cute.make_tensor(tmem_ptr + self.tmem_o0_offset, tCtO_fake.layout)
|
||||
# Use epilogue_tma_store with a fresh consumer state
|
||||
# The acc_pipe is the pipeline we already consumed from, but
|
||||
# epilogue_tma_store wants a consumer. Since we already have O,
|
||||
# skip the acc_pipe wait by using a dummy pipeline.
|
||||
# Actually, just do a simple TMA copy from sC
|
||||
# For the minimal test, just signal the epilogue and move on
|
||||
epi_handle.commit()
|
||||
final_o.release()
|
||||
cute.arch.mbarrier_arrive(st.tmem_dealloc)
|
||||
|
||||
# ==================== EPILOGUE WARP (10) ====================
|
||||
if warp_idx == self.epi_warp_id:
|
||||
epi_handle = corr_epi_cons.wait_and_advance()
|
||||
epi_handle.release()
|
||||
|
||||
|
||||
def test():
|
||||
torch.manual_seed(42)
|
||||
for n in [128]:
|
||||
m, hd = 128, HEAD_DIM
|
||||
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')
|
||||
qf = q[:,:,0].float(); kf = k[:,:,0].float()
|
||||
ref = (qf @ kf.T).bfloat16().float() @ v.float()
|
||||
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))
|
||||
stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
|
||||
kernel = FmhaV3StageCMin(s_k=n)
|
||||
print(f'n={n}: Compiling...', flush=True)
|
||||
compiled = cute.compile(kernel, mQ, mK, mV, mC, stream)
|
||||
print(f'n={n}: Running...', flush=True)
|
||||
compiled(mQ, mK, mV, mC, stream)
|
||||
torch.cuda.synchronize()
|
||||
out = c[:,:,0].float()
|
||||
cos = torch.nn.functional.cosine_similarity(out.flatten().unsqueeze(0), ref.flatten().unsqueeze(0)).item()
|
||||
print(f'FMHA stage-C min n={n}: cosine {cos:.6f}')
|
||||
|
||||
if __name__ == '__main__':
|
||||
test()
|
||||
Reference in New Issue
Block a user