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

317 lines
15 KiB
Python

"""
D1.3 SMEM-P: Diagnostic for make_cotiled_copy approach.
Runs a minimal kernel that:
1. Prints tiled_tmem_load TV layout shapes
2. Prints tTMEM_LOADcS coordinate partition shapes
3. Prints sP layout shapes
4. Attempts to build make_cotiled_copy and prints partition shapes
"""
import torch, math
import cutlass, cutlass.cute as cute, cutlass.utils as utils
from cutlass.cute.nvgpu import cpasync, tcgen05
from cutlass import Float32, BFloat16, Int32, const_expr
from cutlass.utils import LayoutEnum
from cutlass.utils.tmem_allocator import find_tmem_tensor_col_offset
import cutlass.torch as ct
import cuda.bindings.driver as cuda
class SmemPDiag:
def __init__(self, head_dim=64, s_k=128):
self.head_dim = head_dim
self.s_k = s_k
self.pv_n_tile = min(head_dim, 256)
self.use_smem_p = True # We're diagnosing SMEM-P
self.normalize = False
self.qk_mma_tiler = (128, 128, 128 * 4)
self.pv_mma_tiler = (128, self.pv_n_tile, 128)
self.acc_dtype = Float32
self.qk_acc_dtype = Float32
self.q_dtype = BFloat16
self.o_dtype = BFloat16
self.use_2cta_instrs = False
self.cta_group = tcgen05.CtaGroup.ONE
self.cluster_shape_mn = (1, 1)
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_acc_stage = 1
self.scale_softmax_log2 = 1.0 / math.sqrt(self.head_dim) * math.log2(math.e)
self.kv_stage = 2
self.q_stage = 1
self.num_c_stage = 2
self.c_layout = LayoutEnum.ROW_MAJOR
@cute.jit
def __call__(self, q, k, v, c, stream):
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(
(self.pv_n_tile, self.s_k, 1),
stride=(1, self.pv_n_tile, self.pv_n_tile * self.s_k),
),
)
self.v_major = LayoutEnum.from_tensor(v_fmha).mma_major_mode()
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_a_major = cute.nvgpu.OperandMajorMode.K # SMEM-P uses K major
pv_mma = utils.sm100.make_trivial_tiled_mma(
self.q_dtype, self.q_dtype, pv_a_major, self.v_major,
self.qk_acc_dtype, self.cta_group, (128, self.pv_n_tile),
tcgen05.OperandSource.SMEM
)
# Setup TMEM offsets (simplified for SMEM-P)
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 = -1 # SMEM-P
self.tmem_o0_offset = 0
s_cols = self.qk_mma_tiler[1]
o_cols = find_tmem_tensor_col_offset(tOtO)
total = max(s_cols, o_cols)
_n = 1
while _n < total:
_n *= 2
self.num_tmem_alloc_cols = _n
self.tOrP0_offset = 0 # SMEM-P
# Build SMEM layouts
p_smem_s = utils.sm100.make_smem_layout_a(pv_mma, self.pv_mma_tiler, self.q_dtype, 1)
q_smem_s = utils.sm100.make_smem_layout_a(qk_mma, self.qk_mma_tiler, self.q_dtype, self.q_stage)
k_smem_s = utils.sm100.make_smem_layout_b(qk_mma, self.qk_mma_tiler, self.q_dtype, self.kv_stage)
v_smem_s = utils.sm100.make_smem_layout_b(pv_mma, self.pv_mma_tiler, self.q_dtype, self.kv_stage)
c_smem_s = utils.sm100.make_smem_layout_epi(self.o_dtype, self.c_layout, (128, self.pv_n_tile), 2)
# TMA atoms
q_s = cute.slice_(q_smem_s, (None, None, None, 0))
k_s = cute.slice_(k_smem_s, (None, None, None, 0))
v_s = cute.slice_(v_smem_s, (None, None, None, 0))
cta = cute.size(qk_mma.thr_id.shape)
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) + cute.size_in_bytes(self.q_dtype, v_s)) * cta
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, (1, 1, 1, 1)
)
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, (1, 1, 1, 1)
)
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, (1, 1, 1, 1)
)
epi_s = cute.select(c_smem_s, mode=[0, 1])
tma_c, mC = cpasync.make_tiled_tma_atom(cpasync.CopyBulkTensorTileS2GOp(), c, epi_s, (128, self.pv_n_tile))
# ===== KERNEL =====
self._kernel(qk_mma, pv_mma, tma_q, mQ, tma_k, mK, tma_v, mV, tma_c, mC,
p_smem_s, q_smem_s, k_smem_s, v_smem_s, c_smem_s,
tStS, tOtO, qk_thr, pv_thr).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,
p_smem_s, q_smem_s, k_smem_s, v_smem_s, c_smem_s,
tStS, tOtO, qk_thr, pv_thr):
tidx, _, _ = cute.arch.thread_idx()
warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx())
@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)
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)
sP = smem.allocate_tensor(element_type=self.q_dtype, layout=p_smem_s.outer, byte_alignment=128, swizzle=p_smem_s.inner)
# ===== PRINT DIAGNOSTICS (only from warp 0, thread 0) =====
if warp_idx < 4: # softmax warps
# TMEM load atoms
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, tStS)
sfw_idx = tidx % (32 * len(self.epilogue_warp_id))
thr_load = tiled_tmem_load.get_slice(sfw_idx)
tTMEM_LOADtS = thr_load.partition_S(tStS)
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)
if sfw_idx == 0:
print(f"=== TMEM Load Diagnostics (sfw_idx=0) ===")
print(f"tiled_tmem_load shape: {cute.shape(tiled_tmem_load)}")
print(f"tTMEM_LOADtS shape: {cute.shape(tTMEM_LOADtS)}")
print(f"tTMEM_LOADtS layout: {tTMEM_LOADtS.layout}")
print(f"tTMEM_LOADcS shape: {cute.shape(tTMEM_LOADcS)}")
print(f"tTMEM_LOADcS layout: {tTMEM_LOADcS.layout}")
# Print TV layout
tv = tiled_tmem_load.layout_dst_tv_tiled
print(f"TV layout: {tv}")
print(f"TV layout shape: {cute.shape(tv)}")
# Print sP layout
sP_stage = sP[(None, None, None, 0)]
print(f"sP shape: {cute.shape(sP)}")
print(f"sP layout (outer): {sP.layout}")
print(f"sP_stage shape: {cute.shape(sP_stage)}")
print(f"sP_stage layout: {sP_stage.layout}")
# Print tStS layout
print(f"tStS shape: {cute.shape(tStS)}")
print(f"tStS layout: {tStS.layout}")
# Try to build make_cotiled_copy
# atom_layout_tv: (tid, vid) -> sP flat address
# We need to map from the TV layout's codomain (tStS addresses)
# to sP addresses.
#
# tStS layout: ((128,128),1,1):((65536,1),0,0)
# So tStS_addr(m,k) = m*65536 + k
# sP layout: ((128,16),1,(4,2),1):(((64,1),0,((16,8192),0)
# So sP_addr((m,k0),0,(k1,k2),0) = m*64 + k0 + k1*16 + k2*8192
# where k0=k%16, k1=(k//16)%4, k2=k//64
#
# We can't directly compose because the codomains are different.
# But we CAN build a new Layout that maps (tid, vid) -> sP addr.
#
# The key: enumerate all (tid, vid) pairs, find their (m, k) from
# tTMEM_LOADcS, then compute sP_addr.
# But we can't do this at Python trace time inside @cute.kernel
# because we don't have the actual coordinate values.
#
# OR: we can try composition. Let's see if
# cute.composition(sP_stage.layout, tv) works.
# This requires the codomain of tv to be compatible with
# the domain of sP_stage.layout.
print(f"\n=== Attempting composition ===")
print(f"TV codomain size: {cute.size(tv)}")
print(f"sP_stage domain size: {cute.size(sP_stage.layout)}")
# Try: make a layout that maps (m, k) -> sP_addr
# then compose with the inverse of tStS.layout
# Actually, tStS has 3 modes. Let me flatten it.
# The 2D logical P is (128, 128) = (M, K)
# tStS has layout ((128,128),1,1):((65536,1),0,0)
# The 2D part is (128,128) with strides (65536, 1)
# So the 2D layout is: (128, 128) : (65536, 1)
# sP_stage has shape ((128,16),1,(4,2),1)
# The logical P is 128 x 128 where:
# mode0: (128, 16) with strides (64, 1)
# mode2: (4, 2) with strides (16, 8192)
# So the 2D logical layout (grouping modes 0 and 2) is:
# (128*4, 16*2) = (512, 32) with... complex strides.
# Actually, sP is 4D, not 2D.
# Let me try the group_modes approach:
sP_2d = cute.group_modes(sP_stage, 0, 4) # flatten to 1D? No.
# group_modes(sP, 0, 4) makes it (N,) where N = total elements
# Actually group_modes(sP, 0, 4) groups the first 4 modes into 1
# and keeps the rest. sP_stage has 4 modes -> becomes 1 mode.
# That's just a 1D tensor.
print(f"sP_2d (grouped) shape: {cute.shape(sP_2d)}")
print(f"sP_2d layout: {sP_2d.layout}")
# Now try to compose the TV layout with the identity tensor's layout
# to get (tid, vid) -> (m, k), then use that to index into sP.
# Actually, the right approach per the CUTLASS LLM:
# 1. Build a custom atom_layout_tv from scratch
# 2. Each thread's (m, k) pairs come from tTMEM_LOADcS
# 3. Convert (m, k) to sP address
# 4. Build a Layout((n_threads, n_vals_per_thread), (sP_addr_strides,))
#
# But building this at trace time requires knowing all (m, k) values.
# The identity tensor partition tTMEM_LOADcS has these values
# but they're runtime values in CuTeDSL, not Python values.
#
# HOWEVER: since tTMEM_LOADcS is an identity tensor partition,
# the coordinates are STATIC (known at compile/trace time).
# We should be able to extract them at Python trace time.
#
# Let me check: can we iterate over tTMEM_LOADcS at trace time?
# tTMEM_LOADcS has shape ((32,1),4,1,1)
# Each element is a (m, k) pair.
# At trace time, cute.shape gives us the static shape.
# But the actual coordinate VALUES might be dynamic.
#
# In CuTe, identity tensors have static values.
# cute.make_identity_tensor((M, K)) creates a tensor where
# the value at each coordinate IS the coordinate.
# So tTMEM_LOADcS[j0, j1, 0, 0] should give a static (m, k) pair.
# At trace time, we should be able to extract these.
#
# But wait - at trace time, the identity tensor is being traced.
# The values are MLIR constants, not Python ints.
# We can't iterate and build a Python Layout from them.
#
# The alternative: define atom_layout_tv analytically.
# The Ld32x32bOp with Repetition(32) partitions 128 threads
# over a 128x128 matrix. We need to figure out the exact
# (tid, vid) -> (m, k) mapping analytically.
# Let me print what we know about the TMEM load's thread mapping.
# The layout_dst_tv_tiled is a Layout with shape (n_threads, n_vals).
print(f"\n=== Analyzing TV layout for analytical construction ===")
print(f"TV layout type: {type(tv)}")
# Try to decompose it
if hasattr(tv, 'shape'):
print(f" shape: {tv.shape}")
if hasattr(tv, 'stride'):
print(f" stride: {tv.stride}")
def test_cotiled_diag():
print("=== make_cotiled_copy Diagnostic ===\n")
hd = 64
q = torch.randn(128, hd, 1, dtype=torch.bfloat16, device='cuda')
k = torch.randn(128, hd, 1, dtype=torch.bfloat16, device='cuda')
v = torch.randn(128, min(hd, 256), dtype=torch.bfloat16, device='cuda')
c = torch.zeros(128, min(hd, 256), 1, dtype=torch.bfloat16, device='cuda')
diag = SmemPDiag(head_dim=hd, s_k=128)
stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
v_tile = v.unsqueeze(-1)
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_tile).mark_layout_dynamic(leading_dim=ct.get_leading_dim(v_tile))
mC = ct.from_dlpack(c).mark_layout_dynamic(leading_dim=ct.get_leading_dim(c))
print('Compiling diagnostic kernel...', flush=True)
compiled = cute.compile(diag, mQ, mK, mV, mC, stream)
print('Running...', flush=True)
compiled(mQ, mK, mV, mC, stream)
torch.cuda.synchronize()
print('Done.')
if __name__ == '__main__':
test_cotiled_diag()