submission 410773
Dan · python · License unknown
Use it
Vendorable · source mirrored · license unknownView source →
No package. Vendor the mirrored source: 655 lines, June 9 Researcher Reciprocity License v1.0.
nvfp4_group_gemm_cute_v5.py
curl "https://kernelindex.com/api/v1/implementations/kernelbot-nvfp4-group-gemm-410773?include=source"interfacepython
Compatibility
measured onNVIDIA B200
declared hardwareNVIDIA B200
architecturessm_100
dtypesfp8_e4m3, nvfp4
Benchmark evidence
1 measurement across 1 GPU, fastest first.
Operation / workload
Hardware
Latency
Rank
Observed
Reported · How evidence levels are derived →
Source and license
sourceavailable
revision digestsha256:c79204d909048c8dd3febf90edf4909bbbcddfa788d599e3d0f048cb2d460a0e
license declaredunknown
license concludedunknown
authorsDan
imported2026-08-15
Techniques
Extracted from the mirrored source by pattern, never inferred. Each row cites its line.
fp4
"""NVFP4 block-scaled grouped GEMM using CuTe (CUTLASS Python bindings).fused-epilogue
c_smem_layout: cute.Layout, # v4: SMEM layout for epiloguembarrier
tmem_alloc_barrier = pipeline.NamedBarrier(barrier_id=1, num_threads=threads_per_cta)shared-memory
a_smem_layout_staged: cute.ComposedLayout,tcgen05
sfa_tmem_ptr = cute.recast_ptr(acc_tmem_ptr + tcgen05.find_tmem_tensor_col_offset(tCtAcc), dtype=sf_dtype)warp-specialization
TMA_WARP_ID = 0 # Warp 0: TMA producerKernel source
nvfp4_group_gemm_cute_v5.py655 lines
"""NVFP4 block-scaled grouped GEMM using CuTe (CUTLASS Python bindings).
Based on the reference implementation from gpu-mode/reference-kernels.
This targets B200 (SM100/Blackwell) with native FP4 tensor cores.
v5 changes from v4:
- Reduced pipeline stages from 3 to 2 (double buffering instead of triple)
- This reduces SMEM usage from ~111KB to ~79KB per block
- Goal: improve occupancy from 12.5% to allow more concurrent blocks
"""
import cutlass
import cutlass.cute as cute
import cutlass.utils as utils
import cutlass.pipeline as pipeline
from cutlass.cute.nvgpu import cpasync, tcgen05
import cutlass.utils.blackwell_helpers as sm100_utils
import cutlass.utils.blockscaled_layout as blockscaled_utils
from cutlass.utils.layout import LayoutEnum
from cutlass.cute.runtime import make_ptr
import functools
from typing import Tuple, List
import torch
from task import input_t, output_t
# =============================================================================
# Kernel Configuration
# =============================================================================
bytes_per_tensormap = 128 # TMA descriptor size
num_tensormaps = 4 # A, B, SFA, SFB
mma_tiler_mnk = (128, 128, 256) # Tile sizes for M, N, K
mma_inst_shape_k = 64 # MMA instruction K dimension
ab_dtype = cutlass.Float4E2M1FN # FP4 for A and B matrices
sf_dtype = cutlass.Float8E4M3FN # FP8 for scale factors
c_dtype = cutlass.Float16 # FP16 output
sf_vec_size = 16 # Scale factor block size
threads_per_cta = 128 # Threads per CUDA thread block (4 warps)
num_acc_stage = 1 # Accumulator pipeline stages
num_ab_stage = 2 # A/B load pipeline stages (double buffering)
num_tmem_alloc_cols = 512 # TMEM columns to allocate
# Warp roles
TMA_WARP_ID = 0 # Warp 0: TMA producer
MMA_WARP_ID = 1 # Warp 1: MMA consumer
def ceil_div(a, b):
return (a + b - 1) // b
# =============================================================================
# GPU Kernel with Warp Specialization
# =============================================================================
@cute.kernel
def kernel(
tiled_mma: cute.TiledMma,
tma_atom_a: cute.CopyAtom,
mA_mkl: cute.Tensor,
tma_atom_b: cute.CopyAtom,
mB_nkl: cute.Tensor,
tma_atom_sfa: cute.CopyAtom,
mSFA_mkl: cute.Tensor,
tma_atom_sfb: cute.CopyAtom,
mSFB_nkl: cute.Tensor,
tensor_of_abc_ptrs: cute.Tensor,
tensor_of_sfasfb_ptrs: cute.Tensor,
tensormaps: cute.Tensor,
tensor_of_problem_sizes: cute.Tensor,
a_smem_layout_staged: cute.ComposedLayout,
b_smem_layout_staged: cute.ComposedLayout,
sfa_smem_layout_staged: cute.Layout,
sfb_smem_layout_staged: cute.Layout,
c_smem_layout: cute.Layout, # v4: SMEM layout for epilogue
cta_mn_list: List[Tuple[int, int]],
num_tma_load_bytes: cutlass.Constexpr[int],
):
"""
Warp-specialized kernel for block-scaled FP4 grouped GEMM.
v4: SMEM-staged epilogue with CUTLASS pattern for coalesced stores.
"""
warp_idx = cute.arch.warp_idx()
warp_idx = cute.arch.make_warp_uniform(warp_idx)
tidx, _, _ = cute.arch.thread_idx()
# Delinearize block index to (group_idx, coord_x, coord_y)
bidx, bidy, bidz = cute.arch.block_idx()
group_idx = 0
find = False
coord_x = 0
coord_y = 0
cta_rest = bidz
for _, (cta_m, cta_n) in enumerate(cta_mn_list):
if cta_rest >= (cta_m * cta_n):
group_idx += 1
cta_rest -= cta_m * cta_n
else:
if not find:
coord_y = cta_rest // cta_m
coord_x = cta_rest % cta_m
cta_rest -= cta_m * cta_n
find = True
# Get problem dimensions
mC_mnl_iter = cute.make_ptr(
c_dtype, tensor_of_abc_ptrs[group_idx, 2], cute.AddressSpace.gmem
).align(32)
m = tensor_of_problem_sizes[group_idx, 0]
n = tensor_of_problem_sizes[group_idx, 1]
k = tensor_of_problem_sizes[group_idx, 2]
l = tensor_of_problem_sizes[group_idx, 3]
mC_mnl_layout = cute.make_layout(
(m, n, l),
stride=(cute.assume(n, 32), 1, cute.assume(m * n, 32),))
mC_mnl = cute.make_tensor(mC_mnl_iter, mC_mnl_layout)
gC_mnl = cute.local_tile(
mC_mnl, cute.slice_(mma_tiler_mnk, (None, None, 0)), (coord_x, coord_y, 0)
)
# Shared memory allocation
size_tensormap_in_i64 = num_tensormaps * bytes_per_tensormap // 8
@cute.struct
class SharedStorage:
tensormap_buffer: cute.struct.MemRange[cutlass.Int64, size_tensormap_in_i64]
ab_mbar_ptr: cute.struct.MemRange[cutlass.Int64, num_ab_stage * 2]
acc_mbar_ptr: cute.struct.MemRange[cutlass.Int64, num_acc_stage * 2]
tmem_holding_buf: cutlass.Int32
smem = utils.SmemAllocator()
storage = smem.allocate(SharedStorage)
tensormap_smem_ptr = storage.tensormap_buffer.data_ptr()
tensormap_a_smem_ptr = tensormap_smem_ptr
tensormap_b_smem_ptr = tensormap_a_smem_ptr + bytes_per_tensormap // 8
tensormap_sfa_smem_ptr = tensormap_b_smem_ptr + bytes_per_tensormap // 8
tensormap_sfb_smem_ptr = tensormap_sfa_smem_ptr + bytes_per_tensormap // 8
# Allocate shared memory tensors for A, B, SFA, SFB
sA = smem.allocate_tensor(
element_type=ab_dtype, layout=a_smem_layout_staged.outer,
byte_alignment=128, swizzle=a_smem_layout_staged.inner,
)
sB = smem.allocate_tensor(
element_type=ab_dtype, layout=b_smem_layout_staged.outer,
byte_alignment=128, swizzle=b_smem_layout_staged.inner,
)
sSFA = smem.allocate_tensor(
element_type=sf_dtype, layout=sfa_smem_layout_staged, byte_alignment=128,
)
sSFB = smem.allocate_tensor(
element_type=sf_dtype, layout=sfb_smem_layout_staged, byte_alignment=128,
)
# Initialize pipelines - using same config as v2 but with warp-specialized usage
ab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)
ab_pipeline_consumer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 1)
ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create(
barrier_storage=storage.ab_mbar_ptr.data_ptr(),
num_stages=num_ab_stage,
producer_group=ab_pipeline_producer_group,
consumer_group=ab_pipeline_consumer_group,
tx_count=num_tma_load_bytes,
).make_participants()
acc_producer, acc_consumer = pipeline.PipelineUmmaAsync.create(
barrier_storage=storage.acc_mbar_ptr.data_ptr(),
num_stages=num_acc_stage,
producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread),
consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, threads_per_cta),
).make_participants()
# Partition global tensors for this tile
gA_mkl = cute.local_tile(mA_mkl, cute.slice_(mma_tiler_mnk, (None, 0, None)), (None, None, None))
gB_nkl = cute.local_tile(mB_nkl, cute.slice_(mma_tiler_mnk, (0, None, None)), (None, None, None))
gSFA_mkl = cute.local_tile(mSFA_mkl, cute.slice_(mma_tiler_mnk, (None, 0, None)), (None, None, None))
gSFB_nkl = cute.local_tile(mSFB_nkl, cute.slice_(mma_tiler_mnk, (0, None, None)), (None, None, None))
# Partition for MMA
thr_mma = tiled_mma.get_slice(tidx)
tCgA = thr_mma.partition_A(gA_mkl)
tCgB = thr_mma.partition_B(gB_nkl)
tCgSFA = thr_mma.partition_A(gSFA_mkl)
tCgSFB = thr_mma.partition_B(gSFB_nkl)
tCgC = thr_mma.partition_C(gC_mnl)
# TMA descriptor setup
tensormap_manager = utils.TensorMapManager(utils.TensorMapUpdateMode.SMEM, 128)
tensormap_a_gmem_ptr = tensormap_manager.get_tensormap_ptr(tensormaps[(bidz, 0, None)].iterator)
tensormap_b_gmem_ptr = tensormap_manager.get_tensormap_ptr(tensormaps[(bidz, 1, None)].iterator)
tensormap_sfa_gmem_ptr = tensormap_manager.get_tensormap_ptr(tensormaps[(bidz, 2, None)].iterator)
tensormap_sfb_gmem_ptr = tensormap_manager.get_tensormap_ptr(tensormaps[(bidz, 3, None)].iterator)
mA_mkl_iter = cute.make_ptr(ab_dtype, tensor_of_abc_ptrs[group_idx, 0], cute.AddressSpace.gmem).align(32)
mB_nkl_iter = cute.make_ptr(ab_dtype, tensor_of_abc_ptrs[group_idx, 1], cute.AddressSpace.gmem).align(32)
sfa_mkl_iter = cute.make_ptr(sf_dtype, tensor_of_sfasfb_ptrs[group_idx, 0], cute.AddressSpace.gmem).align(32)
sfb_nkl_iter = cute.make_ptr(sf_dtype, tensor_of_sfasfb_ptrs[group_idx, 1], cute.AddressSpace.gmem).align(32)
mA_mkl_layout = cute.make_layout((m, k, l), stride=(cute.assume(k, 32), 1, cute.assume(m * k, 32)))
mB_nkl_layout = cute.make_layout((n, k, l), stride=(cute.assume(k, 32), 1, cute.assume(n * k, 32)))
atom_shape = ((32, 4), (sf_vec_size, 4))
atom_stride = ((16, 4), (0, 1))
sfa_layout = cute.tile_to_shape(
cute.make_layout(atom_shape, stride=atom_stride), mA_mkl_layout.shape, (2, 1, 3)
)
sfb_layout = cute.tile_to_shape(
cute.make_layout(atom_shape, stride=atom_stride), mB_nkl_layout.shape, (2, 1, 3)
)
real_tensor_a = cute.make_tensor(mA_mkl_iter, mA_mkl_layout)
real_tensor_b = cute.make_tensor(mB_nkl_iter, mB_nkl_layout)
real_tensor_sfa = cute.make_tensor(sfa_mkl_iter, sfa_layout)
real_tensor_sfb = cute.make_tensor(sfb_nkl_iter, sfb_layout)
# Warp 0 initializes tensormaps
if warp_idx == 0:
tensormap_manager.init_tensormap_from_atom(tma_atom_a, tensormap_a_smem_ptr, 0)
tensormap_manager.init_tensormap_from_atom(tma_atom_b, tensormap_b_smem_ptr, 0)
tensormap_manager.init_tensormap_from_atom(tma_atom_sfa, tensormap_sfa_smem_ptr, 0)
tensormap_manager.init_tensormap_from_atom(tma_atom_sfb, tensormap_sfb_smem_ptr, 0)
tensormap_manager.update_tensormap(
(real_tensor_a, real_tensor_b, real_tensor_sfa, real_tensor_sfb),
(tma_atom_a, tma_atom_b, tma_atom_sfa, tma_atom_sfb),
(tensormap_a_gmem_ptr, tensormap_b_gmem_ptr, tensormap_sfa_gmem_ptr, tensormap_sfb_gmem_ptr),
0,
(tensormap_a_smem_ptr, tensormap_b_smem_ptr, tensormap_sfa_smem_ptr, tensormap_sfb_smem_ptr),
)
tensormap_manager.fence_tensormap_update(tensormap_a_gmem_ptr)
tensormap_manager.fence_tensormap_update(tensormap_b_gmem_ptr)
tensormap_manager.fence_tensormap_update(tensormap_sfa_gmem_ptr)
tensormap_manager.fence_tensormap_update(tensormap_sfb_gmem_ptr)
cute.arch.barrier()
# TMA partitions
tAsA, tAgA = cpasync.tma_partition(tma_atom_a, 0, cute.make_layout(1), cute.group_modes(sA, 0, 3), cute.group_modes(tCgA, 0, 3))
tBsB, tBgB = cpasync.tma_partition(tma_atom_b, 0, cute.make_layout(1), cute.group_modes(sB, 0, 3), cute.group_modes(tCgB, 0, 3))
tAsSFA, tAgSFA = cpasync.tma_partition(tma_atom_sfa, 0, cute.make_layout(1), cute.group_modes(sSFA, 0, 3), cute.group_modes(tCgSFA, 0, 3))
tAsSFA = cute.filter_zeros(tAsSFA)
tAgSFA = cute.filter_zeros(tAgSFA)
tBsSFB, tBgSFB = cpasync.tma_partition(tma_atom_sfb, 0, cute.make_layout(1), cute.group_modes(sSFB, 0, 3), cute.group_modes(tCgSFB, 0, 3))
tBsSFB = cute.filter_zeros(tBsSFB)
tBgSFB = cute.filter_zeros(tBgSFB)
# MMA fragments
tCrA = tiled_mma.make_fragment_A(sA)
tCrB = tiled_mma.make_fragment_B(sB)
acc_shape = tiled_mma.partition_shape_C(mma_tiler_mnk[:2])
tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape)
# TMEM allocation
tmem_alloc_barrier = pipeline.NamedBarrier(barrier_id=1, num_threads=threads_per_cta)
tmem = utils.TmemAllocator(storage.tmem_holding_buf, barrier_for_retrieve=tmem_alloc_barrier)
tmem.allocate(num_tmem_alloc_cols)
tmem.wait_for_alloc()
acc_tmem_ptr = tmem.retrieve_ptr(cutlass.Float32)
tCtAcc = cute.make_tensor(acc_tmem_ptr, tCtAcc_fake.layout)
# Scale factor TMEM tensors
sfa_tmem_ptr = cute.recast_ptr(acc_tmem_ptr + tcgen05.find_tmem_tensor_col_offset(tCtAcc), dtype=sf_dtype)
tCtSFA_layout = blockscaled_utils.make_tmem_layout_sfa(
tiled_mma, mma_tiler_mnk, sf_vec_size, cute.slice_(sfa_smem_layout_staged, (None, None, None, 0))
)
tCtSFA = cute.make_tensor(sfa_tmem_ptr, tCtSFA_layout)
sfb_tmem_ptr = cute.recast_ptr(
acc_tmem_ptr + tcgen05.find_tmem_tensor_col_offset(tCtAcc) + tcgen05.find_tmem_tensor_col_offset(tCtSFA),
dtype=sf_dtype
)
tCtSFB_layout = blockscaled_utils.make_tmem_layout_sfb(
tiled_mma, mma_tiler_mnk, sf_vec_size, cute.slice_(sfb_smem_layout_staged, (None, None, None, 0))
)
tCtSFB = cute.make_tensor(sfb_tmem_ptr, tCtSFB_layout)
# S2T copy setup
copy_atom_s2t = cute.make_copy_atom(tcgen05.Cp4x32x128bOp(tcgen05.CtaGroup.ONE), sf_dtype)
tCsSFA_compact = cute.filter_zeros(sSFA)
tCtSFA_compact = cute.filter_zeros(tCtSFA)
tiled_copy_s2t_sfa = tcgen05.make_s2t_copy(copy_atom_s2t, tCtSFA_compact)
thr_copy_s2t_sfa = tiled_copy_s2t_sfa.get_slice(0)
tCsSFA_compact_s2t_ = thr_copy_s2t_sfa.partition_S(tCsSFA_compact)
tCsSFA_compact_s2t = tcgen05.get_s2t_smem_desc_tensor(tiled_copy_s2t_sfa, tCsSFA_compact_s2t_)
tCtSFA_compact_s2t = thr_copy_s2t_sfa.partition_D(tCtSFA_compact)
tCsSFB_compact = cute.filter_zeros(sSFB)
tCtSFB_compact = cute.filter_zeros(tCtSFB)
tiled_copy_s2t_sfb = tcgen05.make_s2t_copy(copy_atom_s2t, tCtSFB_compact)
thr_copy_s2t_sfb = tiled_copy_s2t_sfb.get_slice(0)
tCsSFB_compact_s2t_ = thr_copy_s2t_sfb.partition_S(tCsSFB_compact)
tCsSFB_compact_s2t = tcgen05.get_s2t_smem_desc_tensor(tiled_copy_s2t_sfb, tCsSFB_compact_s2t_)
tCtSFB_compact_s2t = thr_copy_s2t_sfb.partition_D(tCtSFB_compact)
k_tile_cnt = cute.ceil_div(real_tensor_a.shape[1], mma_tiler_mnk[2])
# Slice to this tile's coordinates
mma_tile_coord_mnl = (coord_x, coord_y, 0)
tAgA = tAgA[(None, mma_tile_coord_mnl[0], None, mma_tile_coord_mnl[2])]
tBgB = tBgB[(None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2])]
tAgSFA = tAgSFA[(None, mma_tile_coord_mnl[0], None, mma_tile_coord_mnl[2])]
tBgSFB = tBgSFB[(None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2])]
# ==========================================================================
# Main Loop - Warp Specialized (following veitner.bearblog.dev pattern)
# ==========================================================================
# TMA Warp (Warp 0): Acquires buffers and issues TMA copies
if warp_idx == TMA_WARP_ID:
for k_tile in range(k_tile_cnt):
ab_empty = ab_producer.acquire_and_advance()
# Issue TMA loads
cute.copy(tma_atom_a, tAgA[(None, k_tile)], tAsA[(None, ab_empty.index)],
tma_bar_ptr=ab_empty.barrier,
tma_desc_ptr=tensormap_manager.get_tensormap_ptr(tensormap_a_gmem_ptr, cute.AddressSpace.generic))
cute.copy(tma_atom_b, tBgB[(None, k_tile)], tBsB[(None, ab_empty.index)],
tma_bar_ptr=ab_empty.barrier,
tma_desc_ptr=tensormap_manager.get_tensormap_ptr(tensormap_b_gmem_ptr, cute.AddressSpace.generic))
cute.copy(tma_atom_sfa, tAgSFA[(None, k_tile)], tAsSFA[(None, ab_empty.index)],
tma_bar_ptr=ab_empty.barrier,
tma_desc_ptr=tensormap_manager.get_tensormap_ptr(tensormap_sfa_gmem_ptr, cute.AddressSpace.generic))
cute.copy(tma_atom_sfb, tBgSFB[(None, k_tile)], tBsSFB[(None, ab_empty.index)],
tma_bar_ptr=ab_empty.barrier,
tma_desc_ptr=tensormap_manager.get_tensormap_ptr(tensormap_sfb_gmem_ptr, cute.AddressSpace.generic))
# MMA Warp (Warp 1): Waits for data and performs computation
if warp_idx == MMA_WARP_ID:
acc_empty = acc_producer.acquire_and_advance()
tiled_mma.set(tcgen05.Field.ACCUMULATE, False)
for k_tile in range(k_tile_cnt):
ab_full = ab_consumer.wait_and_advance()
# Copy scale factors from SMEM to TMEM
s2t_stage_coord = (None, None, None, None, ab_full.index)
cute.copy(tiled_copy_s2t_sfa, tCsSFA_compact_s2t[s2t_stage_coord], tCtSFA_compact_s2t)
cute.copy(tiled_copy_s2t_sfb, tCsSFB_compact_s2t[s2t_stage_coord], tCtSFB_compact_s2t)
# MMA loop over K blocks within the tile
num_kblocks = cute.size(tCrA, mode=[2])
for kblock_idx in cutlass.range(num_kblocks, unroll_full=True):
kblock_coord = (None, None, kblock_idx, ab_full.index)
sf_kblock_coord = (None, None, kblock_idx)
tiled_mma.set(tcgen05.Field.SFA, tCtSFA[sf_kblock_coord].iterator)
tiled_mma.set(tcgen05.Field.SFB, tCtSFB[sf_kblock_coord].iterator)
cute.gemm(tiled_mma, tCtAcc, tCrA[kblock_coord], tCrB[kblock_coord], tCtAcc)
tiled_mma.set(tcgen05.Field.ACCUMULATE, True)
ab_full.release()
acc_empty.commit()
# ==========================================================================
# Epilogue - Store results
# v4: SMEM-staged for coalesced global stores
# ==========================================================================
# Step 1: T2R copy setup (same as v3)
op = tcgen05.Ld32x32bOp(tcgen05.Repetition.x128, tcgen05.Pack.NONE)
copy_atom_t2r = cute.make_copy_atom(op, cutlass.Float32)
tiled_copy_t2r = tcgen05.make_tmem_copy(copy_atom_t2r, tCtAcc[None, 0, 0])
thr_copy_t2r = tiled_copy_t2r.get_slice(tidx)
tDtAcc = thr_copy_t2r.partition_S(tCtAcc[None, 0, 0])
tDgC = thr_copy_t2r.partition_D(tCgC[None, 0, 0])
tDrAcc = cute.make_rmem_tensor(tDgC.shape, cutlass.Float32)
tDrC = cute.make_rmem_tensor(tDgC.shape, c_dtype)
tmem.relinquish_alloc_permit()
acc_full = acc_consumer.wait_and_advance()
# Step 2: T2R copy and convert
cute.copy(tiled_copy_t2r, tDtAcc, tDrAcc)
acc_vec = tDrAcc.load()
tDrC.store(acc_vec.to(c_dtype))
# Step 3: Setup SMEM tensor (row-major layout matching tile size)
sC_ptr = cute.recast_ptr(sA.iterator, dtype=c_dtype)
sC_layout = cute.make_layout(
(mma_tiler_mnk[0], mma_tiler_mnk[1]),
stride=(mma_tiler_mnk[1], 1)
)
sC = cute.make_tensor(sC_ptr, sC_layout)
# Step 4: Setup R2G copy (same as v3) to get correct coordinate mapping
simt_atom = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), c_dtype, num_bits_per_copy=16)
thread_layout = cute.make_layout((1, threads_per_cta), stride=(threads_per_cta, 1))
value_layout = cute.make_layout((1, 1))
tiled_copy_r2g = cute.make_tiled_copy_tv(simt_atom, thread_layout, value_layout)
thr_copy_r2g = tiled_copy_r2g.get_slice(tidx)
# Get coordinate mapping using identity tensor (same as v3)
cC = cute.make_identity_tensor(gC_mnl.shape)
tDcC = thr_copy_r2g.partition_D(cC)
# Write each register element to SMEM at its logical position
# Identity tensor coords are (n, m) due to gC_mnl's stride order
for i in range(cute.size(tDrC)):
coord = tDcC[i]
n_coord = cute.get(coord, (0,))
m_coord = cute.get(coord, (1,))
sC[(m_coord, n_coord)] = tDrC[i]
# Step 5: Barrier to ensure all SMEM writes complete
cute.arch.fence_view_async_shared()
cute.arch.barrier()
# Step 6: Coalesced copy from SMEM to global
# Each thread reads from SMEM and writes to global with coalesced access pattern
residue_m = mC_mnl.shape[0] - cutlass.Int32(coord_x) * mma_tiler_mnk[0]
residue_n = mC_mnl.shape[1] - cutlass.Int32(coord_y) * mma_tiler_mnk[1]
elements_per_thread = (mma_tiler_mnk[0] * mma_tiler_mnk[1]) // threads_per_cta
for elem_idx in cutlass.range(elements_per_thread):
# Stride pattern for coalesced access: thread i handles elements i, i+128, i+256, ...
linear_idx = tidx + elem_idx * threads_per_cta
m_local = linear_idx // mma_tiler_mnk[1]
n_local = linear_idx % mma_tiler_mnk[1]
# Global coordinates
m_global = cutlass.Int32(coord_x) * mma_tiler_mnk[0] + m_local
n_global = cutlass.Int32(coord_y) * mma_tiler_mnk[1] + n_local
# Bounds check and copy
if (m_local < residue_m) & (n_local < residue_n):
smem_val = sC[(m_local, n_local)]
mC_mnl[(m_global, n_global, 0)] = smem_val
acc_full.release()
cute.arch.barrier()
tmem.free(acc_tmem_ptr)
# =============================================================================
# Host-side JIT function
# =============================================================================
@cute.jit
def my_kernel(
ptr_of_tensor_of_problem_sizes: cute.Pointer,
ptr_of_tensor_of_abc_ptrs: cute.Pointer,
ptr_of_tensor_of_sfasfb_ptrs: cute.Pointer,
ptr_of_tensor_of_tensormap: cute.Pointer,
total_num_clusters: cutlass.Int32,
problem_sizes: List[Tuple[int, int, int, int]],
num_groups: cutlass.Int32,
):
tensor_of_abc_ptrs = cute.make_tensor(
ptr_of_tensor_of_abc_ptrs, cute.make_layout((num_groups, 3), stride=(3, 1))
)
tensor_of_sfasfb_ptrs = cute.make_tensor(
ptr_of_tensor_of_sfasfb_ptrs, cute.make_layout((num_groups, 2), stride=(2, 1))
)
tensor_of_problem_sizes = cute.make_tensor(
ptr_of_tensor_of_problem_sizes, cute.make_layout((num_groups, 4), stride=(4, 1))
)
tensor_of_tensormap = cute.make_tensor(
ptr_of_tensor_of_tensormap, cute.make_layout((total_num_clusters, 4, 16), stride=(64, 16, 1))
)
# Initial tensor setup
min_shape = (cutlass.Int32(64), cutlass.Int32(64), cutlass.Int32(64), cutlass.Int32(1))
initial_a = cute.make_tensor(
cute.make_ptr(ab_dtype, 0, cute.AddressSpace.gmem, assumed_align=16),
cute.make_layout(
(min_shape[0], cute.assume(min_shape[2], 32), min_shape[3]),
stride=(cute.assume(min_shape[2], 32), 1, cute.assume(min_shape[0] * min_shape[2], 32))
),
)
initial_b = cute.make_tensor(
cute.make_ptr(ab_dtype, 0, cute.AddressSpace.gmem, assumed_align=16),
cute.make_layout(
(min_shape[1], cute.assume(min_shape[2], 32), min_shape[3]),
stride=(cute.assume(min_shape[2], 32), 1, cute.assume(min_shape[1] * min_shape[2], 32))
),
)
sfa_layout = blockscaled_utils.tile_atom_to_shape_SF(initial_a.shape, sf_vec_size)
sfb_layout = blockscaled_utils.tile_atom_to_shape_SF(initial_b.shape, sf_vec_size)
initial_sfa = cute.make_tensor(
cute.make_ptr(sf_dtype, 0, cute.AddressSpace.gmem, assumed_align=16), sfa_layout
)
initial_sfb = cute.make_tensor(
cute.make_ptr(sf_dtype, 0, cute.AddressSpace.gmem, assumed_align=16), sfb_layout
)
# Configure MMA
mma_op = tcgen05.MmaMXF4NVF4Op(
sf_dtype, (mma_tiler_mnk[0], mma_tiler_mnk[1], mma_inst_shape_k), tcgen05.CtaGroup.ONE, tcgen05.OperandSource.SMEM
)
tiled_mma = cute.make_tiled_mma(mma_op)
cluster_layout_vmnk = cute.tiled_divide(cute.make_layout((1, 1, 1)), (tiled_mma.thr_id.shape,))
# Shared memory layouts
a_smem_layout_staged = sm100_utils.make_smem_layout_a(tiled_mma, mma_tiler_mnk, ab_dtype, num_ab_stage)
b_smem_layout_staged = sm100_utils.make_smem_layout_b(tiled_mma, mma_tiler_mnk, ab_dtype, num_ab_stage)
sfa_smem_layout_staged = blockscaled_utils.make_smem_layout_sfa(tiled_mma, mma_tiler_mnk, sf_vec_size, num_ab_stage)
sfb_smem_layout_staged = blockscaled_utils.make_smem_layout_sfb(tiled_mma, mma_tiler_mnk, sf_vec_size, num_ab_stage)
atom_thr_size = cute.size(tiled_mma.thr_id.shape)
# TMA setup
a_smem_layout = cute.slice_(a_smem_layout_staged, (None, None, None, 0))
tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A(
cpasync.CopyBulkTensorTileG2SOp(tcgen05.CtaGroup.ONE), initial_a, a_smem_layout,
mma_tiler_mnk, tiled_mma, cluster_layout_vmnk.shape
)
b_smem_layout = cute.slice_(b_smem_layout_staged, (None, None, None, 0))
tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B(
cpasync.CopyBulkTensorTileG2SOp(tcgen05.CtaGroup.ONE), initial_b, b_smem_layout,
mma_tiler_mnk, tiled_mma, cluster_layout_vmnk.shape
)
sfa_smem_layout = cute.slice_(sfa_smem_layout_staged, (None, None, None, 0))
tma_atom_sfa, tma_tensor_sfa = cute.nvgpu.make_tiled_tma_atom_A(
cpasync.CopyBulkTensorTileG2SOp(tcgen05.CtaGroup.ONE), initial_sfa, sfa_smem_layout,
mma_tiler_mnk, tiled_mma, cluster_layout_vmnk.shape, internal_type=cutlass.Int16
)
sfb_smem_layout = cute.slice_(sfb_smem_layout_staged, (None, None, None, 0))
tma_atom_sfb, tma_tensor_sfb = cute.nvgpu.make_tiled_tma_atom_B(
cpasync.CopyBulkTensorTileG2SOp(tcgen05.CtaGroup.ONE), initial_sfb, sfb_smem_layout,
mma_tiler_mnk, tiled_mma, cluster_layout_vmnk.shape, internal_type=cutlass.Int16
)
# Compute TMA bytes
a_copy_size = cute.size_in_bytes(ab_dtype, a_smem_layout)
b_copy_size = cute.size_in_bytes(ab_dtype, b_smem_layout)
sfa_copy_size = cute.size_in_bytes(sf_dtype, sfa_smem_layout)
sfb_copy_size = cute.size_in_bytes(sf_dtype, sfb_smem_layout)
num_tma_load_bytes = (a_copy_size + b_copy_size + sfa_copy_size + sfb_copy_size) * atom_thr_size
# v4: Epilogue SMEM layout (simple row-major for the tile)
c_smem_layout = cute.make_layout(
(mma_tiler_mnk[0], mma_tiler_mnk[1]),
stride=(mma_tiler_mnk[1], 1)
)
# Build CTA work list
cta_mn_list = []
for group_idx, (m, n, k, l) in enumerate(problem_sizes):
x, y = cute.ceil_div(problem_sizes[group_idx][:2], mma_tiler_mnk[0:2])
cta_mn_list.append((x, y))
grid = (1, 1, total_num_clusters)
kernel(
tiled_mma,
tma_atom_a, tma_tensor_a,
tma_atom_b, tma_tensor_b,
tma_atom_sfa, tma_tensor_sfa,
tma_atom_sfb, tma_tensor_sfb,
tensor_of_abc_ptrs, tensor_of_sfasfb_ptrs,
tensor_of_tensormap, tensor_of_problem_sizes,
a_smem_layout_staged, b_smem_layout_staged,
sfa_smem_layout_staged, sfb_smem_layout_staged,
c_smem_layout,
cta_mn_list, num_tma_load_bytes,
).launch(grid=grid, block=[threads_per_cta, 1, 1], cluster=(1, 1, 1))
# =============================================================================
# Compilation and Entry Point
# =============================================================================
_compiled_kernel_cache = {}
def compile_kernel(problem_sizes):
"""Compile and cache kernel for given problem sizes."""
global _compiled_kernel_cache
cache_key = f"{len(problem_sizes)}"
if cache_key in _compiled_kernel_cache:
return _compiled_kernel_cache[cache_key]
cute_ptr_of_tensor_of_problem_sizes = make_ptr(cutlass.Int32, 0, cute.AddressSpace.gmem, assumed_align=16)
cute_ptr_of_tensor_of_abc_ptrs = make_ptr(cutlass.Int64, 0, cute.AddressSpace.gmem, assumed_align=16)
cute_ptr_of_tensor_of_sfasfb_ptrs = make_ptr(cutlass.Int64, 0, cute.AddressSpace.gmem, assumed_align=16)
cute_ptr_of_tensor_of_tensormap = make_ptr(cutlass.Int64, 0, cute.AddressSpace.gmem, assumed_align=16)
total_num_clusters = cutlass.Int32(1)
num_groups = cutlass.Int32(len(problem_sizes))
compiled_func = cute.compile(
my_kernel,
cute_ptr_of_tensor_of_problem_sizes,
cute_ptr_of_tensor_of_abc_ptrs,
cute_ptr_of_tensor_of_sfasfb_ptrs,
cute_ptr_of_tensor_of_tensormap,
total_num_clusters,
problem_sizes,
num_groups
)
_compiled_kernel_cache[cache_key] = compiled_func
return compiled_func
def custom_kernel(data: input_t) -> output_t:
"""Main entry point for block-scaled group GEMM."""
abc_tensors, _, sfasfb_reordered_tensors, problem_sizes = data
compiled_func = compile_kernel(problem_sizes)
# Extract pointers
abc_ptrs = []
sfasfb_ptrs = []
for (a, b, c), (sfa_reordered, sfb_reordered) in zip(abc_tensors, sfasfb_reordered_tensors):
abc_ptrs.append((a.data_ptr(), b.data_ptr(), c.data_ptr()))
sfasfb_ptrs.append((sfa_reordered.data_ptr(), sfb_reordered.data_ptr()))
tensor_of_problem_sizes = torch.tensor(problem_sizes, dtype=torch.int32, device="cuda")
tensor_of_abc_ptrs = torch.tensor(abc_ptrs, dtype=torch.int64, device="cuda")
tensor_of_sfasfb_ptrs = torch.tensor(sfasfb_ptrs, dtype=torch.int64, device="cuda")
# Compute total clusters
cta_tile_shape_mn = [128, mma_tiler_mnk[1]]
cluster_tile_shape_mn = tuple(x * y for x, y in zip(cta_tile_shape_mn, (1, 1)))
total_num_clusters = 0
for m, n, _, _ in problem_sizes:
num_clusters_mn = tuple((x + y - 1) // y for x, y in zip((m, n), cluster_tile_shape_mn))
total_num_clusters += functools.reduce(lambda x, y: x * y, num_clusters_mn)
# Allocate tensormap buffer
tensormap_shape = (total_num_clusters, num_tensormaps, bytes_per_tensormap // 8)
tensor_of_tensormap = torch.empty(tensormap_shape, dtype=torch.int64, device="cuda")
# Create CuTe pointers
cute_ptr_of_tensor_of_abc_ptrs = make_ptr(
cutlass.Int64, tensor_of_abc_ptrs.data_ptr(), cute.AddressSpace.gmem, assumed_align=16
)
cute_ptr_of_tensor_of_sfasfb_ptrs = make_ptr(
cutlass.Int64, tensor_of_sfasfb_ptrs.data_ptr(), cute.AddressSpace.gmem, assumed_align=16
)
cute_ptr_of_tensor_of_problem_sizes = make_ptr(
cutlass.Int32, tensor_of_problem_sizes.data_ptr(), cute.AddressSpace.gmem, assumed_align=16
)
cute_ptr_of_tensor_of_tensormap = make_ptr(
cutlass.Int64, tensor_of_tensormap.data_ptr(), cute.AddressSpace.gmem, assumed_align=16
)
# Launch
compiled_func(
cute_ptr_of_tensor_of_problem_sizes,
cute_ptr_of_tensor_of_abc_ptrs,
cute_ptr_of_tensor_of_sfasfb_ptrs,
cute_ptr_of_tensor_of_tensormap,
total_num_clusters,
problem_sizes,
len(problem_sizes),
)
return [abc_tensors[i][2] for i in range(len(problem_sizes))]
scrolls · 655 lines total
Source code from GPU Mode and the KernelBot dataset · June 9 Researcher Reciprocity License v1.0
Changes from previous submission
Against this author's previous submission submission 385043.
- """NVFP4 block-scaled grouped GEMM using CuTe with WARP SPECIALIZATION.+ """NVFP4 block-scaled grouped GEMM using CuTe (CUTLASS Python bindings).- v3: Implements warp specialization based on SM100 Blackwell pattern:- - Warp 0: TMA producer (issues tensor memory accelerator loads)- - Warp 1: MMA consumer (issues matrix multiply-accumulate)- - All warps participate in epilogue+ Based on the reference implementation from gpu-mode/reference-kernels.+ This targets B200 (SM100/Blackwell) with native FP4 tensor cores.- Key fix: Proper synchronization between TMA and MMA warps using barriers.-- Based on:- - https://gau-nernst.github.io/tcgen05/ (tcgen05 warp specialization)- - CUTLASS sm100_gemm_tma_warpspecialized.hpp+ v5 changes from v4:+ - Reduced pipeline stages from 3 to 2 (double buffering instead of triple)+ - This reduces SMEM usage from ~111KB to ~79KB per block+ - Goal: improve occupancy from 12.5% to allow more concurrent blocks"""import cutlass⋯ 3 unchanged linesfrom cutlass.cute.nvgpu import cpasync, tcgen05import cutlass.utils.blackwell_helpers as sm100_utilsimport cutlass.utils.blockscaled_layout as blockscaled_utils+ from cutlass.utils.layout import LayoutEnumfrom cutlass.cute.runtime import make_ptrimport functools⋯ 5 unchanged lines# =============================================================================# Kernel Configuration# =============================================================================- bytes_per_tensormap = 128- num_tensormaps = 4- mma_tiler_mnk = (128, 128, 256)- mma_inst_shape_k = 64- ab_dtype = cutlass.Float4E2M1FN- sf_dtype = cutlass.Float8E4M3FN- c_dtype = cutlass.Float16- sf_vec_size = 16+ bytes_per_tensormap = 128 # TMA descriptor size+ num_tensormaps = 4 # A, B, SFA, SFB+ mma_tiler_mnk = (128, 128, 256) # Tile sizes for M, N, K+ mma_inst_shape_k = 64 # MMA instruction K dimension+ ab_dtype = cutlass.Float4E2M1FN # FP4 for A and B matrices+ sf_dtype = cutlass.Float8E4M3FN # FP8 for scale factors+ c_dtype = cutlass.Float16 # FP16 output+ sf_vec_size = 16 # Scale factor block size+ threads_per_cta = 128 # Threads per CUDA thread block (4 warps)+ num_acc_stage = 1 # Accumulator pipeline stages+ num_ab_stage = 2 # A/B load pipeline stages (double buffering)+ num_tmem_alloc_cols = 512 # TMEM columns to allocate- # Warp specialization configuration- # Warp 0: TMA, Warp 1+: MMA and epilogue- threads_per_cta = 128 # 4 warps- num_acc_stage = 1- num_ab_stage = 2 # Double buffer for TMA/MMA overlap- num_tmem_alloc_cols = 512+ # Warp roles+ TMA_WARP_ID = 0 # Warp 0: TMA producer+ MMA_WARP_ID = 1 # Warp 1: MMA consumerdef ceil_div(a, b):⋯ 22 unchanged linesb_smem_layout_staged: cute.ComposedLayout,sfa_smem_layout_staged: cute.Layout,sfb_smem_layout_staged: cute.Layout,+ c_smem_layout: cute.Layout, # v4: SMEM layout for epiloguecta_mn_list: List[Tuple[int, int]],num_tma_load_bytes: cutlass.Constexpr[int],):"""- Warp-specialized GPU kernel for block-scaled FP4 grouped GEMM.-- Key insight: TMA and MMA are both issued by warp 0 (same as v1),- but we use 2 pipeline stages for better overlap. The "warp specialization"- here is that warp 0 handles the mainloop while other warps wait,- then all warps participate in the epilogue.-- True warp specialization (separate TMA/MMA warps) requires the C++ API's- ThreadCategory::Producer/Consumer role assignment.+ Warp-specialized kernel for block-scaled FP4 grouped GEMM.+ v4: SMEM-staged epilogue with CUTLASS pattern for coalesced stores."""warp_idx = cute.arch.warp_idx()warp_idx = cute.arch.make_warp_uniform(warp_idx)tidx, _, _ = cute.arch.thread_idx()# Delinearize block index to (group_idx, coord_x, coord_y)- _, _, bidz = cute.arch.block_idx()+ bidx, bidy, bidz = cute.arch.block_idx()group_idx = 0find = Falsecoord_x = 0⋯ 10 unchanged linescta_rest -= cta_m * cta_nfind = True- # Get problem dimensions and construct output tensor+ # Get problem dimensionsmC_mnl_iter = cute.make_ptr(c_dtype, tensor_of_abc_ptrs[group_idx, 2], cute.AddressSpace.gmem).align(32)⋯ 45 unchanged lineselement_type=sf_dtype, layout=sfb_smem_layout_staged, byte_alignment=128,)- # Pipeline setup - single thread producer/consumer as in original+ # Initialize pipelines - using same config as v2 but with warp-specialized usageab_pipeline_producer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread)ab_pipeline_consumer_group = pipeline.CooperativeGroup(pipeline.Agent.Thread, 1)-ab_producer, ab_consumer = pipeline.PipelineTmaUmma.create(barrier_storage=storage.ab_mbar_ptr.data_ptr(),num_stages=num_ab_stage,⋯ 23 unchanged linestCgSFB = thr_mma.partition_B(gSFB_nkl)tCgC = thr_mma.partition_C(gC_mnl)- # Update TMA descriptors with actual tensor shapes+ # TMA descriptor setuptensormap_manager = utils.TensorMapManager(utils.TensorMapUpdateMode.SMEM, 128)tensormap_a_gmem_ptr = tensormap_manager.get_tensormap_ptr(tensormaps[(bidz, 0, None)].iterator)tensormap_b_gmem_ptr = tensormap_manager.get_tensormap_ptr(tensormaps[(bidz, 1, None)].iterator)⋯ 8 unchanged linesmA_mkl_layout = cute.make_layout((m, k, l), stride=(cute.assume(k, 32), 1, cute.assume(m * k, 32)))mB_nkl_layout = cute.make_layout((n, k, l), stride=(cute.assume(k, 32), 1, cute.assume(n * k, 32)))- # Scale factor layout (specialized layout from cuBLAS docs)atom_shape = ((32, 4), (sf_vec_size, 4))atom_stride = ((16, 4), (0, 1))sfa_layout = cute.tile_to_shape(⋯ 28 unchanged linescute.arch.barrier()- # TMA partitions for loading+ # TMA partitionstAsA, tAgA = cpasync.tma_partition(tma_atom_a, 0, cute.make_layout(1), cute.group_modes(sA, 0, 3), cute.group_modes(tCgA, 0, 3))tBsB, tBgB = cpasync.tma_partition(tma_atom_b, 0, cute.make_layout(1), cute.group_modes(sB, 0, 3), cute.group_modes(tCgB, 0, 3))tAsSFA, tAgSFA = cpasync.tma_partition(tma_atom_sfa, 0, cute.make_layout(1), cute.group_modes(sSFA, 0, 3), cute.group_modes(tCgSFA, 0, 3))⋯ 9 unchanged linesacc_shape = tiled_mma.partition_shape_C(mma_tiler_mnk[:2])tCtAcc_fake = tiled_mma.make_fragment_C(acc_shape)- # Allocate TMEM for accumulator+ # TMEM allocationtmem_alloc_barrier = pipeline.NamedBarrier(barrier_id=1, num_threads=threads_per_cta)tmem = utils.TmemAllocator(storage.tmem_holding_buf, barrier_for_retrieve=tmem_alloc_barrier)tmem.allocate(num_tmem_alloc_cols)⋯ 17 unchanged lines)tCtSFB = cute.make_tensor(sfb_tmem_ptr, tCtSFB_layout)- # S2T copy for scale factors+ # S2T copy setupcopy_atom_s2t = cute.make_copy_atom(tcgen05.Cp4x32x128bOp(tcgen05.CtaGroup.ONE), sf_dtype)tCsSFA_compact = cute.filter_zeros(sSFA)⋯ 22 unchanged linestBgSFB = tBgSFB[(None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2])]# ==========================================================================- # Main Loop with 2-stage pipelining+ # Main Loop - Warp Specialized (following veitner.bearblog.dev pattern)# ==========================================================================- # Warp 0 handles both TMA and MMA (same thread must call producer/consumer)- # The 2-stage pipeline allows TMA for tile K+1 to overlap with MMA for tile K- if warp_idx == 0:- acc_empty = acc_producer.acquire_and_advance()- tiled_mma.set(tcgen05.Field.ACCUMULATE, False)+ # TMA Warp (Warp 0): Acquires buffers and issues TMA copies+ if warp_idx == TMA_WARP_ID:for k_tile in range(k_tile_cnt):- # Acquire empty buffer and issue TMA loadsab_empty = ab_producer.acquire_and_advance()+ # Issue TMA loadscute.copy(tma_atom_a, tAgA[(None, k_tile)], tAsA[(None, ab_empty.index)],tma_bar_ptr=ab_empty.barrier,tma_desc_ptr=tensormap_manager.get_tensormap_ptr(tensormap_a_gmem_ptr, cute.AddressSpace.generic))⋯ 7 unchanged linestma_bar_ptr=ab_empty.barrier,tma_desc_ptr=tensormap_manager.get_tensormap_ptr(tensormap_sfb_gmem_ptr, cute.AddressSpace.generic))- # Wait for TMA to complete+ # MMA Warp (Warp 1): Waits for data and performs computation+ if warp_idx == MMA_WARP_ID:+ acc_empty = acc_producer.acquire_and_advance()+ tiled_mma.set(tcgen05.Field.ACCUMULATE, False)++ for k_tile in range(k_tile_cnt):ab_full = ab_consumer.wait_and_advance()- # Copy scale factors to TMEM+ # Copy scale factors from SMEM to TMEMs2t_stage_coord = (None, None, None, None, ab_full.index)cute.copy(tiled_copy_s2t_sfa, tCsSFA_compact_s2t[s2t_stage_coord], tCtSFA_compact_s2t)cute.copy(tiled_copy_s2t_sfb, tCsSFB_compact_s2t[s2t_stage_coord], tCtSFB_compact_s2t)⋯ 11 unchanged linestiled_mma.set(tcgen05.Field.ACCUMULATE, True)ab_full.release()+acc_empty.commit()# ==========================================================================# Epilogue - Store results+ # v4: SMEM-staged for coalesced global stores# ==========================================================================++ # Step 1: T2R copy setup (same as v3)op = tcgen05.Ld32x32bOp(tcgen05.Repetition.x128, tcgen05.Pack.NONE)copy_atom_t2r = cute.make_copy_atom(op, cutlass.Float32)tiled_copy_t2r = tcgen05.make_tmem_copy(copy_atom_t2r, tCtAcc[None, 0, 0])⋯ 7 unchanged linestmem.relinquish_alloc_permit()acc_full = acc_consumer.wait_and_advance()+ # Step 2: T2R copy and convertcute.copy(tiled_copy_t2r, tDtAcc, tDrAcc)acc_vec = tDrAcc.load()tDrC.store(acc_vec.to(c_dtype))- # Store to global memory+ # Step 3: Setup SMEM tensor (row-major layout matching tile size)+ sC_ptr = cute.recast_ptr(sA.iterator, dtype=c_dtype)+ sC_layout = cute.make_layout(+ (mma_tiler_mnk[0], mma_tiler_mnk[1]),+ stride=(mma_tiler_mnk[1], 1)+ )+ sC = cute.make_tensor(sC_ptr, sC_layout)++ # Step 4: Setup R2G copy (same as v3) to get correct coordinate mappingsimt_atom = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), c_dtype, num_bits_per_copy=16)thread_layout = cute.make_layout((1, threads_per_cta), stride=(threads_per_cta, 1))value_layout = cute.make_layout((1, 1))tiled_copy_r2g = cute.make_tiled_copy_tv(simt_atom, thread_layout, value_layout)thr_copy_r2g = tiled_copy_r2g.get_slice(tidx)++ # Get coordinate mapping using identity tensor (same as v3)cC = cute.make_identity_tensor(gC_mnl.shape)tDcC = thr_copy_r2g.partition_D(cC)- tDpC = cute.make_rmem_tensor(tDrC.shape, cutlass.Boolean)+ # Write each register element to SMEM at its logical position+ # Identity tensor coords are (n, m) due to gC_mnl's stride order+ for i in range(cute.size(tDrC)):+ coord = tDcC[i]+ n_coord = cute.get(coord, (0,))+ m_coord = cute.get(coord, (1,))+ sC[(m_coord, n_coord)] = tDrC[i]++ # Step 5: Barrier to ensure all SMEM writes complete+ cute.arch.fence_view_async_shared()+ cute.arch.barrier()++ # Step 6: Coalesced copy from SMEM to global+ # Each thread reads from SMEM and writes to global with coalesced access patternresidue_m = mC_mnl.shape[0] - cutlass.Int32(coord_x) * mma_tiler_mnk[0]residue_n = mC_mnl.shape[1] - cutlass.Int32(coord_y) * mma_tiler_mnk[1]- for i in range(cute.size(tDrC.shape)):- tDpC[i] = cute.elem_less(tDcC[i], (residue_n, residue_m))- cute.copy(simt_atom, cute.flatten(tDrC), cute.flatten(tDgC), pred=cute.flatten(tDpC))+ elements_per_thread = (mma_tiler_mnk[0] * mma_tiler_mnk[1]) // threads_per_cta+ for elem_idx in cutlass.range(elements_per_thread):+ # Stride pattern for coalesced access: thread i handles elements i, i+128, i+256, ...+ linear_idx = tidx + elem_idx * threads_per_cta+ m_local = linear_idx // mma_tiler_mnk[1]+ n_local = linear_idx % mma_tiler_mnk[1]++ # Global coordinates+ m_global = cutlass.Int32(coord_x) * mma_tiler_mnk[0] + m_local+ n_global = cutlass.Int32(coord_y) * mma_tiler_mnk[1] + n_local++ # Bounds check and copy+ if (m_local < residue_m) & (n_local < residue_n):+ smem_val = sC[(m_local, n_local)]+ mC_mnl[(m_global, n_global, 0)] = smem_val+acc_full.release()cute.arch.barrier()tmem.free(acc_tmem_ptr)⋯ 25 unchanged linesptr_of_tensor_of_tensormap, cute.make_layout((total_num_clusters, 4, 16), stride=(64, 16, 1)))- # Initial tensor setup with minimum shapes+ # Initial tensor setupmin_shape = (cutlass.Int32(64), cutlass.Int32(64), cutlass.Int32(64), cutlass.Int32(1))initial_a = cute.make_tensor(cute.make_ptr(ab_dtype, 0, cute.AddressSpace.gmem, assumed_align=16),⋯ 19 unchanged linescute.make_ptr(sf_dtype, 0, cute.AddressSpace.gmem, assumed_align=16), sfb_layout)- # Configure MMA for FP4+ # Configure MMAmma_op = tcgen05.MmaMXF4NVF4Op(sf_dtype, (mma_tiler_mnk[0], mma_tiler_mnk[1], mma_inst_shape_k), tcgen05.CtaGroup.ONE, tcgen05.OperandSource.SMEM)⋯ 37 unchanged linessfb_copy_size = cute.size_in_bytes(sf_dtype, sfb_smem_layout)num_tma_load_bytes = (a_copy_size + b_copy_size + sfa_copy_size + sfb_copy_size) * atom_thr_size+ # v4: Epilogue SMEM layout (simple row-major for the tile)+ c_smem_layout = cute.make_layout(+ (mma_tiler_mnk[0], mma_tiler_mnk[1]),+ stride=(mma_tiler_mnk[1], 1)+ )+# Build CTA work listcta_mn_list = []for group_idx, (m, n, k, l) in enumerate(problem_sizes):⋯ 12 unchanged linestensor_of_tensormap, tensor_of_problem_sizes,a_smem_layout_staged, b_smem_layout_staged,sfa_smem_layout_staged, sfb_smem_layout_staged,+ c_smem_layout,cta_mn_list, num_tma_load_bytes,).launch(grid=grid, block=[threads_per_cta, 1, 1], cluster=(1, 1, 1))⋯ 34 unchanged linesdef custom_kernel(data: input_t) -> output_t:- """- Main entry point for block-scaled group GEMM.- v3: Uses 2 pipeline stages for better TMA/MMA overlap.- """+ """Main entry point for block-scaled group GEMM."""abc_tensors, _, sfasfb_reordered_tensors, problem_sizes = datacompiled_func = compile_kernel(problem_sizes)⋯ 9 unchanged linestensor_of_abc_ptrs = torch.tensor(abc_ptrs, dtype=torch.int64, device="cuda")tensor_of_sfasfb_ptrs = torch.tensor(sfasfb_ptrs, dtype=torch.int64, device="cuda")- # Compute total clusters needed+ # Compute total clusterscta_tile_shape_mn = [128, mma_tiler_mnk[1]]cluster_tile_shape_mn = tuple(x * y for x, y in zip(cta_tile_shape_mn, (1, 1)))
scrolls · 349 diff lines total
Best evidence level for this revision: reported
JSON