From ec6e08c979c8b90b0ea3eb345ed568702adfbefb Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Mon, 30 Nov 2026 14:51:53 +0000 Subject: [PATCH] perf(b12x/moe): optimize W4A8 inline 1-bit CSF staging and register-direct decode --- .../b12x/_lib/quant/csf_inline.py | 683 +++++++++++++++++- .../kernels/w4a8_compact_projection.py | 557 ++++++++------ .../b12x/moe/_shared/kernels/w4a8_phase1.py | 439 ++++++----- .../b12x/moe/_shared/kernels/w4a8_phase2.py | 304 ++++---- .../b12x/moe/fused_moe/_tuning.py | 2 +- tests/experimental/b12x/moe/test_mxfp4_csf.py | 180 +++++ 6 files changed, 1626 insertions(+), 539 deletions(-) diff --git a/flashinfer/experimental/b12x/_lib/quant/csf_inline.py b/flashinfer/experimental/b12x/_lib/quant/csf_inline.py index 0bf15d88261..54a898d736e 100644 --- a/flashinfer/experimental/b12x/_lib/quant/csf_inline.py +++ b/flashinfer/experimental/b12x/_lib/quant/csf_inline.py @@ -2,12 +2,17 @@ import cutlass import cutlass.cute as cute -from cutlass.cutlass_dsl import Int32, Int64, Uint32 +from cutlass.cutlass_dsl import Int32, Int64, Uint32, Uint64 from b12x._lib.intrinsics.packed import byte_perm from b12x._lib.intrinsics.memory import ( cp_async4_shared_global, + cp_async4_shared_global_l2hint, cp_async_u32_shared_global, + cp_async_u32_shared_global_l2hint, + ld_shared_u16_zx_ordered, + ld_shared_v2_u32, + ld_shared_v4_u32, st_shared_u8, st_shared_v4_u32, ld_global_nc_u32, @@ -16,6 +21,9 @@ from b12x._lib.quant.csf_blocks import CompactBlockStoragePlane +COMPACT_1BIT_SLOT_BYTES = 256 + + class CsfInlineReader: def __init__(self, geometry): if len(geometry) != 11 or geometry[3] != 9: @@ -95,6 +103,679 @@ def prefetch_row_bases(self, storage, expert, row_group, lane): word = ld_global_nc_u32((storage + offset).toint()) return word + @property + def compact_1bit_bounds_bytes(self) -> int: + """Aligned SMEM bytes to cache one row group's (first, end) bounds + 8B value_offset.""" + return ((self.plane.storage.column_groups * 8 + 8 + 15) // 16) * 16 + + @property + def compact_1bit_vo_offset(self) -> int: + """8-byte aligned offset of cached value_offset inside bounds_smem.""" + return self.plane.storage.column_groups * 8 + + @cute.jit + def prefetch_column_bounds_smem( + self, + storage, + source_expert, + row_group, + dst_smem, + tid, + *, + num_threads: cutlass.Constexpr = 32, + sync_warp_after: cutlass.Constexpr = False, + ): + """Cache one row group's (first, end) bounds and value_offset in SMEM. + + Supports 32-thread (1-warp) or 64-thread (2-warp) cooperative prefetch. + All chunk global loads are issued into registers before SMEM stores so + multi-chunk geometries (e.g. K=5120, 40 column groups) overlap in flight. + The CTA sync_threads before the first decode publishes all writes. + """ + storage = cute.recast_ptr(storage, dtype=cutlass.Uint8) + groups = self.plane.storage.column_groups + n_chunks = (groups + num_threads - 1) // num_threads + if tid < Int32(num_threads): + firsts = cute.make_rmem_tensor((n_chunks,), Uint32) + ends = cute.make_rmem_tensor((n_chunks,), Uint32) + for chunk in cutlass.range_constexpr(n_chunks): + col = tid + Int32(chunk * num_threads) + if col < Int32(groups): + group = row_group * Int32(groups) + col + f, e = self.plane.group_record_bounds(storage, source_expert, group) + firsts[chunk] = f + ends[chunk] = e + vo_u64 = Uint64(0) + if tid == Int32(31): + vo_u64 = self.plane.group_value_offset(storage).to(Uint64) + for chunk in cutlass.range_constexpr(n_chunks): + col = tid + Int32(chunk * num_threads) + if col < Int32(groups): + st_shared_u32(dst_smem + (col << Int32(3)), firsts[chunk]) + st_shared_u32(dst_smem + (col << Int32(3)) + Int32(4), ends[chunk]) + if tid == Int32(31): + st_shared_u32( + dst_smem + Int32(self.compact_1bit_vo_offset), + (vo_u64 & Uint64(0xFFFFFFFF)).to(Uint32), + ) + st_shared_u32( + dst_smem + Int32(self.compact_1bit_vo_offset + 4), + (vo_u64 >> Uint64(32)).to(Uint32), + ) + if cutlass.const_expr(sync_warp_after): + if tid < Int32(32): + cute.arch.sync_warp() + + @cute.jit + def load_lane_bases_packed( + self, + storage, + source_expert, + row_group, + r0, + *, + row_stride: cutlass.Constexpr, + n_fragments: cutlass.Constexpr, + ): + """Load this lane's invariant row base bytes into one packed Uint32.""" + storage = cute.recast_ptr(storage, dtype=cutlass.Uint8) + row_base = row_group * Int32(128) + nr = cutlass.min(Int32(128), Int32(self.plane.storage.rows) - row_base) + expert_base = Int64(self.plane.storage.bases) + ( + source_expert * Int32(self.plane.storage.rows) + row_base + ).to(Int64) + packed = Uint32(0) + for nt in cutlass.range_constexpr(n_fragments): + r = r0 + Int32(nt * row_stride) + if r < nr: + aligned = (r >> Int32(2)) << Int32(2) + w = ld_global_nc_u32((storage + expert_base + aligned.to(Int64)).toint()) + b = (w >> ((r & Int32(3)) << Int32(3)).to(Uint32)) & Uint32(255) + packed = packed | (b << Uint32(nt * 8)) + return packed + + @cute.jit + def load_lane_pair_bases_packed( + self, + storage, + gate_expert, + up_expert, + row_group, + r0, + *, + row_stride: cutlass.Constexpr, + ): + """Pack 2 gate + 2 up row bases for one lane into a single Uint32.""" + storage = cute.recast_ptr(storage, dtype=cutlass.Uint8) + row_base = row_group * Int32(128) + nr = cutlass.min(Int32(128), Int32(self.plane.storage.rows) - row_base) + gate_base = Int64(self.plane.storage.bases) + ( + gate_expert * Int32(self.plane.storage.rows) + row_base + ).to(Int64) + up_base = Int64(self.plane.storage.bases) + ( + up_expert * Int32(self.plane.storage.rows) + row_base + ).to(Int64) + packed = Uint32(0) + for nt in cutlass.range_constexpr(2): + r = r0 + Int32(nt * row_stride) + if r < nr: + aligned = (r >> Int32(2)) << Int32(2) + sh = ((r & Int32(3)) << Int32(3)).to(Uint32) + gb = ( + ld_global_nc_u32((storage + gate_base + aligned.to(Int64)).toint()) + >> sh + ) & Uint32(255) + ub = ( + ld_global_nc_u32((storage + up_base + aligned.to(Int64)).toint()) + >> sh + ) & Uint32(255) + packed = packed | (gb << Uint32(nt * 8)) | (ub << Uint32((nt + 2) * 8)) + return packed + + @cute.jit + def stage_compact_1bit_codes( + self, + storage, + expert, + target_addr, + lane, + coordinates, + *, + half_idx=None, + l2_policy=None, + ): + """Issue 1-bit code cp.async copies immediately with zero bounds dependency.""" + assert self.plane.destination == 3 and self.plane.storage.bits == 1 + storage = cute.recast_ptr(storage, dtype=cutlass.Uint8) + section, row_group, column_group = coordinates + source_expert = expert * Int32(self.plane.sections) + section + if cutlass.const_expr(self.plane.storage.rows % 128 == 0): + nr = Int32(128) + else: + nr = cutlass.min( + Int32(128), Int32(self.plane.storage.rows) - row_group * Int32(128) + ) + if cutlass.const_expr(self.plane.columns % 4 == 0): + nc = Int32(4) + else: + nc = cutlass.min( + Int32(4), Int32(self.plane.columns) - column_group * Int32(4) + ) + codes = ( + Int64(self.plane.storage.codes) + + source_expert.to(Int64) * Int64(self.plane.storage.code_bytes) + + row_group.to(Int64) * Int64(128 * self.plane.columns // 8) + + ((column_group * nr).to(Int64) >> Int64(1)) + ) + if cutlass.const_expr(half_idx is not None): + if lane < Int32(2): + src = ( + storage + + codes + + (half_idx << Int32(5)).to(Int64) + + (lane << Int32(4)).to(Int64) + ).toint() + dst = target_addr + (lane << Int32(4)) + if cutlass.const_expr(l2_policy is not None): + cp_async4_shared_global_l2hint(dst, src, l2_policy) + else: + cp_async4_shared_global(dst, src) + else: + code_bytes = (nr * nc) >> Int32(3) + if cutlass.const_expr( + self.plane.storage.rows % 64 == 0 and self.plane.columns % 2 == 0 + ): + if lane < Int32(4) and (lane << Int32(4)) < code_bytes: + src = (storage + codes + (lane << Int32(4)).to(Int64)).toint() + dst = target_addr + (lane << Int32(4)) + if cutlass.const_expr(l2_policy is not None): + cp_async4_shared_global_l2hint(dst, src, l2_policy) + else: + cp_async4_shared_global(dst, src) + else: + if lane < Int32(16) and (lane << Int32(2)) < code_bytes: + src = (storage + codes + (lane << Int32(2)).to(Int64)).toint() + dst = target_addr + (lane << Int32(2)) + if cutlass.const_expr(l2_policy is not None): + cp_async_u32_shared_global_l2hint(dst, src, l2_policy) + else: + cp_async_u32_shared_global(dst, src) + + @cute.jit + def stage_compact_1bit_exceptions( + self, + storage, + target_addr, + lane, + column_group, + *, + bounds_smem, + l2_policy=None, + first_end=None, + ): + """Zero-STS staging of sparse exception positions and values when first < end.""" + assert self.plane.destination == 3 and self.plane.storage.bits == 1 + storage = cute.recast_ptr(storage, dtype=cutlass.Uint8) + if cutlass.const_expr(first_end is not None): + first, end = first_end + else: + first, end = ld_shared_v2_u32(bounds_smem + (column_group << Int32(3))) + if first < end: + vo_lo, vo_hi = ld_shared_v2_u32( + bounds_smem + Int32(self.compact_1bit_vo_offset) + ) + vo = ((vo_hi.to(Uint64) << Uint64(32)) | vo_lo.to(Uint64)).to(Int64) + value_start = vo + first.to(Int64) + count = cutlass.min(end - first, Uint32(32)) + if lane < Int32(17) and (lane.to(Uint32) << Uint32(1)) < count + ( + first & Uint32(1) + ): + src_p = ( + storage + + Int64(self.plane.storage.source_records) + + ((first & ~Uint32(1)).to(Int64) << Int64(1)) + + (lane.to(Int64) << Int64(2)) + ).toint() + dst_p = target_addr + Int32(64) + (lane << Int32(2)) + if cutlass.const_expr(l2_policy is not None): + cp_async_u32_shared_global_l2hint(dst_p, src_p, l2_policy) + else: + cp_async_u32_shared_global(dst_p, src_p) + if lane < Int32(9) and (lane.to(Uint32) << Uint32(2)) < count + ( + value_start & Int64(3) + ): + src_v = ( + storage + + (value_start & ~Int64(3)) + + (lane.to(Int64) << Int64(2)) + ).toint() + dst_v = target_addr + Int32(132) + (lane << Int32(2)) + if cutlass.const_expr(l2_policy is not None): + cp_async_u32_shared_global_l2hint(dst_v, src_v, l2_policy) + else: + cp_async_u32_shared_global(dst_v, src_v) + + @cute.jit + def stage_compact_1bit( + self, + storage, + expert, + target_addr, + lane, + coordinates, + *, + bounds_smem, + half_idx=None, + l2_policy=None, + ): + """Zero-STS staging of 1-bit codes and sparse exceptions into a 256-byte slot. + + Layout (16-byte aligned, <= 168 B used inside 256 B aligned slot): + [0..63] 1-bit codes (32 B when half_idx is set, else nr*nc/8 <= 64 B) + [64..131] up to 32 exception positions (17 x u32, only staged if first < end) + [132..167] up to 32 exception values (9 x u32, only staged if first < end) + """ + # Issue bounds LDS before code staging so its latency overlaps code address + # arithmetic and LDGSTS before the exception branch tests first < end. + first, end = ld_shared_v2_u32(bounds_smem + (coordinates[2] << Int32(3))) + self.stage_compact_1bit_codes( + storage, + expert, + target_addr, + lane, + coordinates, + half_idx=half_idx, + l2_policy=l2_policy, + ) + self.stage_compact_1bit_exceptions( + storage, + target_addr, + lane, + coordinates[2], + bounds_smem=bounds_smem, + l2_policy=l2_policy, + first_end=(first, end), + ) + + @cute.jit + def _patch_compact_1bit_exceptions( + self, + storage, + slot, + vo_bounds_smem, + first, + end, + r0, + dst_words, + *, + nc, + nc_always_4: cutlass.Constexpr, + nc_always_even: cutlass.Constexpr, + row_stride: cutlass.Constexpr, + n_fragments: cutlass.Constexpr, + ): + """Patch register-held scale words with staged (<=32) and overflow (>32) exceptions.""" + staged_count = cutlass.min(end - first, Uint32(32)).to(Int32) + pos_align = (first & Uint32(1)).to(Int32) + match_mask = (n_fragments - 1) * row_stride + for idx in cutlass.range(staged_count, unroll=1): + pos = ld_shared_u16_zx_ordered( + slot + Int32(64) + ((pos_align + idx) << Int32(1)) + ).to(Int32) + if cutlass.const_expr(nc_always_4): + erow = pos >> Int32(2) + ecol = pos & Int32(3) + elif cutlass.const_expr(nc_always_even): + erow = pos >> Int32(1) + ecol = pos & Int32(1) + if nc == Int32(4): + erow = pos >> Int32(2) + ecol = pos & Int32(3) + else: + erow = Int32(0) + ecol = Int32(0) + if nc == Int32(4): + erow = pos >> Int32(2) + ecol = pos & Int32(3) + elif nc == Int32(2): + erow = pos >> Int32(1) + ecol = pos & Int32(1) + elif nc > Int32(0): + erow = pos // nc + ecol = pos % nc + diff = erow - r0 + if (diff & ~Int32(match_mask)) == Int32(0): + vo_lo = ld_shared_u32( + vo_bounds_smem + Int32(self.compact_1bit_vo_offset) + ) + v = ((vo_lo + first) & Uint32(3)).to(Int32) + idx + val = ( + ld_shared_u32(slot + Int32(132) + ((v >> Int32(2)) << Int32(2))) + >> ((v & Int32(3)) << Int32(3)).to(Uint32) + ) & Uint32(255) + sh = (ecol << Int32(3)).to(Uint32) + clear_mask = ~(Uint32(0xFF) << sh) + ins = val << sh + for nt in cutlass.range_constexpr(n_fragments): + if diff == Int32(nt * row_stride): + dst_words[nt] = (dst_words[nt] & clear_mask) | ins + if first + Uint32(32) < end: + vo_lo2, vo_hi2 = ld_shared_v2_u32( + vo_bounds_smem + Int32(self.compact_1bit_vo_offset) + ) + vo = ((vo_hi2.to(Uint64) << Uint64(32)) | vo_lo2.to(Uint64)).to(Int64) + overflow = (end - first - Uint32(32)).to(Int32) + for tail in cutlass.range(overflow, unroll=1): + entry = first + Uint32(32) + tail.to(Uint32) + pos, val_u8 = self.plane.load_group_record(storage, entry, vo) + if cutlass.const_expr(nc_always_4): + erow = pos >> Int32(2) + ecol = pos & Int32(3) + elif cutlass.const_expr(nc_always_even): + erow = pos >> Int32(1) + ecol = pos & Int32(1) + if nc == Int32(4): + erow = pos >> Int32(2) + ecol = pos & Int32(3) + else: + erow = Int32(0) + ecol = Int32(0) + if nc == Int32(4): + erow = pos >> Int32(2) + ecol = pos & Int32(3) + elif nc == Int32(2): + erow = pos >> Int32(1) + ecol = pos & Int32(1) + elif nc > Int32(0): + erow = pos // nc + ecol = pos % nc + diff = erow - r0 + if (diff & ~Int32(match_mask)) == Int32(0): + sh = (ecol << Int32(3)).to(Uint32) + clear_mask = ~(Uint32(0xFF) << sh) + ins = val_u8.to(Uint32) << sh + for nt in cutlass.range_constexpr(n_fragments): + if diff == Int32(nt * row_stride): + dst_words[nt] = (dst_words[nt] & clear_mask) | ins + + @cute.jit + def decode_compact_1bit_words( + self, + storage, + slot, + bounds_smem, + column_group, + bases_packed, + r0, + dst_words, + *, + row_stride: cutlass.Constexpr, + n_fragments: cutlass.Constexpr, + half_offset=None, + nr=None, + base_byte_offset: cutlass.Constexpr = 0, + aligned_v4_codes: cutlass.Constexpr = False, + aligned_v2_codes: cutlass.Constexpr = False, + hoist_bounds: cutlass.Constexpr = True, + ): + """Reconstruct a lane's scale words directly in registers without SMEM scratch or sync.""" + assert self.plane.destination == 3 and self.plane.storage.bits == 1 + assert n_fragments in (1, 2, 4) and row_stride > 0 and (row_stride & (row_stride - 1)) == 0 + storage = cute.recast_ptr(storage, dtype=cutlass.Uint8) + local_r0 = r0 - half_offset if cutlass.const_expr(half_offset is not None) else r0 + nc_always_4 = self.plane.columns % 4 == 0 + nc_always_even = self.plane.columns % 2 == 0 + nc = ( + Int32(4) + if cutlass.const_expr(nc_always_4) + else cutlass.min( + Int32(4), Int32(self.plane.columns) - column_group * Int32(4) + ) + ) + + # Issue bounds LDS before code LDS when register headroom permits so both + # overlap in flight; register-tight kernels set hoist_bounds=False. + first, end = Uint32(0), Uint32(0) + if cutlass.const_expr(hoist_bounds): + first, end = ld_shared_v2_u32(bounds_smem + (column_group << Int32(3))) + if cutlass.const_expr(nc_always_4): + nibble_shift = ((local_r0 & Int32(7)) << Int32(2)).to(Uint32) + base_word_idx = local_r0 >> Int32(3) + if cutlass.const_expr(aligned_v4_codes and n_fragments == 4 and row_stride == 8): + c0, c1, c2, c3 = ld_shared_v4_u32(slot + (base_word_idx << Int32(2))) + code_arr = (c0, c1, c2, c3) + for nt in cutlass.range_constexpr(4): + nib = (code_arr[nt] >> nibble_shift) & Uint32(15) + off = (nib * Uint32(0x00204081)) & Uint32(0x01010101) + b_sel = (base_byte_offset + nt) * 0x1111 + w = byte_perm(bases_packed, Uint32(0), Int32(b_sel)) + off + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + elif cutlass.const_expr(aligned_v2_codes and n_fragments == 2 and row_stride == 8): + c0, c1 = ld_shared_v2_u32(slot + (base_word_idx << Int32(2))) + code_arr = (c0, c1) + for nt in cutlass.range_constexpr(2): + nib = (code_arr[nt] >> nibble_shift) & Uint32(15) + off = (nib * Uint32(0x00204081)) & Uint32(0x01010101) + b_sel = (base_byte_offset + nt) * 0x1111 + w = byte_perm(bases_packed, Uint32(0), Int32(b_sel)) + off + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + else: + for nt in cutlass.range_constexpr(n_fragments): + cword = ld_shared_u32( + slot + ((base_word_idx + Int32(nt * (row_stride // 8))) << Int32(2)) + ) + nib = (cword >> nibble_shift) & Uint32(15) + off = (nib * Uint32(0x00204081)) & Uint32(0x01010101) + b_sel = (base_byte_offset + nt) * 0x1111 + w = byte_perm(bases_packed, Uint32(0), Int32(b_sel)) + off + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + else: + if nc == Int32(4): + nibble_shift = ((local_r0 & Int32(7)) << Int32(2)).to(Uint32) + base_word_idx = local_r0 >> Int32(3) + if cutlass.const_expr(aligned_v4_codes and n_fragments == 4 and row_stride == 8): + c0, c1, c2, c3 = ld_shared_v4_u32(slot + (base_word_idx << Int32(2))) + code_arr = (c0, c1, c2, c3) + for nt in cutlass.range_constexpr(4): + nib = (code_arr[nt] >> nibble_shift) & Uint32(15) + off = (nib * Uint32(0x00204081)) & Uint32(0x01010101) + b_sel = (base_byte_offset + nt) * 0x1111 + w = byte_perm(bases_packed, Uint32(0), Int32(b_sel)) + off + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + else: + for nt in cutlass.range_constexpr(n_fragments): + cword = ld_shared_u32( + slot + ((base_word_idx + Int32(nt * (row_stride // 8))) << Int32(2)) + ) + nib = (cword >> nibble_shift) & Uint32(15) + off = (nib * Uint32(0x00204081)) & Uint32(0x01010101) + b_sel = (base_byte_offset + nt) * 0x1111 + w = byte_perm(bases_packed, Uint32(0), Int32(b_sel)) + off + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + elif nc == Int32(2): + if cutlass.const_expr(aligned_v4_codes and n_fragments == 4 and row_stride == 8): + lo, hi = ld_shared_v2_u32(slot + ((local_r0 >> Int32(4)) << Int32(2))) + q_shift = ((local_r0 & Int32(7)) << Int32(1)).to(Uint32) + c_arr = ( + (lo >> q_shift) & Uint32(3), + (lo >> (q_shift + Uint32(16))) & Uint32(3), + (hi >> q_shift) & Uint32(3), + (hi >> (q_shift + Uint32(16))) & Uint32(3), + ) + for nt in cutlass.range_constexpr(4): + off = (c_arr[nt] * Uint32(0x00204081)) & Uint32(0x01010101) + b_sel = 0x4400 + (base_byte_offset + nt) * 0x0011 + w = byte_perm(bases_packed, Uint32(0), Int32(b_sel)) + off + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + else: + for nt in cutlass.range_constexpr(n_fragments): + lr = local_r0 + Int32(nt * row_stride) + cword = ld_shared_u32(slot + ((lr >> Int32(4)) << Int32(2))) + c2 = (cword >> ((lr & Int32(15)) << Int32(1)).to(Uint32)) & Uint32(3) + off = (c2 * Uint32(0x00204081)) & Uint32(0x01010101) + b_sel = 0x4400 + (base_byte_offset + nt) * 0x0011 + w = byte_perm(bases_packed, Uint32(0), Int32(b_sel)) + off + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + elif cutlass.const_expr(nc_always_even): + for nt in cutlass.range_constexpr(n_fragments): + dst_words[nt] = Uint32(0) + else: + for nt in cutlass.range_constexpr(n_fragments): + w = Uint32(0) + if nc > Int32(0): + lr = local_r0 + Int32(nt * row_stride) + field = lr * nc + shift = field & Int32(31) + codes = ld_shared_u32( + slot + ((field >> Int32(5)) << Int32(2)) + ) >> shift.to(Uint32) + if shift + nc > Int32(32): + codes = codes | ( + ld_shared_u32( + slot + ((field >> Int32(5)) << Int32(2)) + Int32(4) + ) + << (Int32(32) - shift).to(Uint32) + ) + codes = codes & ((Uint32(1) << nc.to(Uint32)) - Uint32(1)) + off = (codes * Uint32(0x00204081)) & Uint32(0x01010101) + b_byte = ( + bases_packed >> Uint32((base_byte_offset + nt) * 8) + ) & Uint32(255) + w = ( + b_byte + * ( + Uint32(0x01010101) + >> ((Int32(4) - nc) * Int32(8)).to(Uint32) + ) + + off + ) + if cutlass.const_expr(nr is not None): + if r0 + Int32(nt * row_stride) >= nr: + w = Uint32(0) + dst_words[nt] = w + + if cutlass.const_expr(not hoist_bounds): + first, end = ld_shared_v2_u32(bounds_smem + (column_group << Int32(3))) + if first < end: + self._patch_compact_1bit_exceptions( + storage, + slot, + bounds_smem, + first, + end, + r0, + dst_words, + nc=nc, + nc_always_4=nc_always_4, + nc_always_even=nc_always_even, + row_stride=row_stride, + n_fragments=n_fragments, + ) + + @cute.jit + def decode_compact_1bit_pair_words( + self, + storage, + gate_slot, + up_slot, + gate_bounds_smem, + column_group, + pair_bases_packed, + local_r0, + half_offset, + gate_words, + up_words, + ): + """Interleaved 1-bit decode for N64 Phase1 gate+up pair (2 rows each, stride 8).""" + assert ( + self.plane.destination == 3 + and self.plane.storage.bits == 1 + and self.plane.columns % 4 == 0 + ) + storage = cute.recast_ptr(storage, dtype=cutlass.Uint8) + up_bounds_smem = gate_bounds_smem + Int32(self.compact_1bit_bounds_bytes) + nibble_shift = ((local_r0 & Int32(7)) << Int32(2)).to(Uint32) + code_byte_off = (local_r0 >> Int32(3)) << Int32(2) + + # Issue all 4 LDS.64 loads back-to-back to maximize LSU ILP. + gc0, gc1 = ld_shared_v2_u32(gate_slot + code_byte_off) + uc0, uc1 = ld_shared_v2_u32(up_slot + code_byte_off) + gf, ge = ld_shared_v2_u32(gate_bounds_smem + (column_group << Int32(3))) + uf, ue = ld_shared_v2_u32(up_bounds_smem + (column_group << Int32(3))) + + gn0 = (gc0 >> nibble_shift) & Uint32(15) + gn1 = (gc1 >> nibble_shift) & Uint32(15) + un0 = (uc0 >> nibble_shift) & Uint32(15) + un1 = (uc1 >> nibble_shift) & Uint32(15) + + gate_words[0] = byte_perm(pair_bases_packed, Uint32(0), Int32(0x0000)) + ( + (gn0 * Uint32(0x00204081)) & Uint32(0x01010101) + ) + gate_words[1] = byte_perm(pair_bases_packed, Uint32(0), Int32(0x1111)) + ( + (gn1 * Uint32(0x00204081)) & Uint32(0x01010101) + ) + up_words[0] = byte_perm(pair_bases_packed, Uint32(0), Int32(0x2222)) + ( + (un0 * Uint32(0x00204081)) & Uint32(0x01010101) + ) + up_words[1] = byte_perm(pair_bases_packed, Uint32(0), Int32(0x3333)) + ( + (un1 * Uint32(0x00204081)) & Uint32(0x01010101) + ) + + # Cold non-unrolled staged exception patcher; direct gf/uf branches avoid loop overhead. + if ((ge - gf) | (ue - uf)) != Uint32(0): + r0 = half_offset + local_r0 + if gf < ge: + self._patch_compact_1bit_exceptions( + storage, + gate_slot, + gate_bounds_smem, + gf, + ge, + r0, + gate_words, + nc=Int32(4), + nc_always_4=True, + nc_always_even=True, + row_stride=8, + n_fragments=2, + ) + if uf < ue: + self._patch_compact_1bit_exceptions( + storage, + up_slot, + gate_bounds_smem, + uf, + ue, + r0, + up_words, + nc=Int32(4), + nc_always_4=True, + nc_always_even=True, + row_stride=8, + n_fragments=2, + ) + @cute.jit def expand_warp_rows(self, storage, slot, rows, warp, lane, value_offset=None): """Rebuild one warp's 32 rows of a staged row-major slot into ``rows``. diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_compact_projection.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_compact_projection.py index 80094cb5b47..8bf899b0b6c 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_compact_projection.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_compact_projection.py @@ -37,6 +37,7 @@ ) from b12x._lib.intrinsics.atomics import ld_shared_u32, st_shared_u32 from b12x._lib.intrinsics.packed import pack_f32x2_to_bfloat2 +from b12x._lib.quant.csf_inline import COMPACT_1BIT_SLOT_BYTES from b12x.moe._shared.kernels.w4a8_compact_activation import ( W4A8CompactMicroActivationKernel, ) @@ -231,13 +232,17 @@ def __init__( self.share_projection_input = False self.n_tiles = (self.n + self.tile_n - 1) // self.tile_n self.b_payload_bytes = self.tile_n * self.tile_k // 2 - self.sfb_bytes = 512 if self.csf_inline else self.tile_n * 4 + self.sfb_bytes = COMPACT_1BIT_SLOT_BYTES if self.csf_inline else self.tile_n * 4 self.a_offset = 0 self.sfa_offset = 128 self.b_offset = 256 self.sfb_offset = self.b_offset + self.b_payload_bytes self.stage_bytes = self.sfb_offset + self.sfb_bytes - self.shared_words = self.stages * self.stage_bytes // 4 + self.csf_bounds_offset = self.stages * self.stage_bytes + self.csf_bounds_bytes = ( + (((self.k // 128) * 8 + 8 + 255) // 256) * 256 if self.csf_inline else 0 + ) + self.shared_words = (self.csf_bounds_offset + self.csf_bounds_bytes) // 4 @cute.jit def __call__( @@ -407,10 +412,9 @@ def _stage_n64_sfb( output_tile: Int32, k128_slice: Int32, tid: Int32, - bounds=None, - value_offset=None, - base_word=None, + bounds_smem=None, l2_policy=None, + prefetch_bounds: cutlass.Constexpr = False, ): physical_tile = output_tile // Int32(128 // self.tile_n) packed_half = output_tile % Int32(128 // self.tile_n) @@ -418,39 +422,51 @@ def _stage_n64_sfb( if physical_tile == Int32(self.n // 128): n_rows = Int32(64) if cutlass.const_expr(self.csf_inline): - if tid < Int32(32): - target = cute.make_ptr( - cutlass.Uint8, dst_base, cute.AddressSpace.smem, assumed_align=16 - ) - group = ( - projection * Int32(self.csf_reader.plane.storage.groups) - + physical_tile * Int32(self.csf_reader.plane.storage.column_groups) - + k128_slice + half_arg = packed_half if cutlass.const_expr(self.tile_n == 64) else None + if cutlass.const_expr(prefetch_bounds): + if tid < Int32(32): + self.csf_reader.stage_compact_1bit_codes( + scales.iterator, + expert_idx, + dst_base, + tid, + (projection, physical_tile, k128_slice), + half_idx=half_arg, + l2_policy=l2_policy, + ) + section_expert = ( + expert_idx * Int32(self.csf_reader.plane.sections) + projection ) - cached = None - if cutlass.const_expr(bounds is not None): - first, end = Uint32(0), Uint32(0) - for chunk in cutlass.range_constexpr(cute.size(bounds, mode=[0])): - selected_first = cute.arch.shuffle_sync( - bounds[chunk, 0], k128_slice % Int32(32) - ) - selected_end = cute.arch.shuffle_sync( - bounds[chunk, 1], k128_slice % Int32(32) - ) - if k128_slice // Int32(32) == Int32(chunk): - first, end = selected_first, selected_end - cached = (first, end) - self.csf_reader.stage_compressed( + self.csf_reader.prefetch_column_bounds_smem( scales.iterator, - expert_idx, - group, - target, + section_expert, + physical_tile, + bounds_smem, tid, - cached, - value_offset, - base_word, - coordinates=(projection, physical_tile, k128_slice), + num_threads=64 if self.threads_per_cta >= 64 else 32, + sync_warp_after=True, ) + if tid < Int32(32): + self.csf_reader.stage_compact_1bit_exceptions( + scales.iterator, + dst_base, + tid, + k128_slice, + bounds_smem=bounds_smem, + l2_policy=l2_policy, + ) + else: + if tid < Int32(32): + self.csf_reader.stage_compact_1bit( + scales.iterator, + expert_idx, + dst_base, + tid, + (projection, physical_tile, k128_slice), + bounds_smem=bounds_smem, + half_idx=half_arg, + l2_policy=l2_policy, + ) return if tid < Int32(self.tile_n // 4): dst_addr = dst_base + (tid << Int32(4)) @@ -497,10 +513,9 @@ def _stage_slice( expert: Int32, projection_tile: Int32, k128_slice: Int32, - csf_bounds=None, - csf_value_offset=None, - csf_base_word=None, + csf_bounds_smem=None, l2_policy=None, + prefetch_bounds: cutlass.Constexpr = False, ): stage_base = smem_base if cutlass.const_expr(self.stages == 2): @@ -552,10 +567,9 @@ def _stage_slice( output_tile, k128_slice, tid, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, l2_policy, + prefetch_bounds=prefetch_bounds, ) else: packed_tile = projection_tile // Int32(2) @@ -621,23 +635,11 @@ def _run_task( input_smem_base -= (projection_tile // Int32(self.n_tiles)) * Int32( self.shared_words * 4 ) - csf_bounds, csf_base_word, csf_value_offset = None, None, None - if cutlass.const_expr(self.csf_inline): - # Each task keeps one validated expert and projection row group - # throughout its K sweep; another persistent-grid task reloads them. - projection = projection_tile // Int32(self.n_tiles) - output_tile = projection_tile % Int32(self.n_tiles) - physical_tile = output_tile // Int32(128 // self.tile_n) - section_expert = expert * Int32(self.csf_reader.plane.sections) + projection - csf_value_offset = self.csf_reader.plane.group_value_offset( - w13_sfb.iterator - ) - csf_bounds = self.csf_reader.prefetch_column_bounds( - w13_sfb.iterator, section_expert, physical_tile - ) - csf_base_word = self.csf_reader.prefetch_row_bases( - w13_sfb.iterator, section_expert, physical_tile, tid - ) + csf_bounds_smem = ( + smem_base + Int32(self.csf_bounds_offset) + if cutlass.const_expr(self.csf_inline) + else None + ) l2_policy = create_l2_evict_first_policy() for preload in cutlass.range_constexpr(1): if cutlass.const_expr(preload < self.k // 128): @@ -652,13 +654,39 @@ def _run_task( expert, projection_tile, Int32(preload), - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, l2_policy, + prefetch_bounds=True, ) cute.arch.cp_async_commit_group() + csf_bases_packed = None + csf_r0, csf_half_offset, csf_nr = Int32(0), Int32(0), Int32(128) + if cutlass.const_expr(self.csf_inline): + # Overlap invariant base-byte loads with committed A[0]+B[0]+codes[0]+exc[0]. + projection = projection_tile // Int32(self.n_tiles) + output_tile = projection_tile % Int32(self.n_tiles) + physical_tile = output_tile // Int32(128 // self.tile_n) + packed_half = output_tile % Int32(128 // self.tile_n) + section_expert = expert * Int32(self.csf_reader.plane.sections) + projection + csf_half_offset = packed_half * Int32(self.tile_n) + csf_r0 = ( + csf_half_offset + + (warp * Int32(self.n_fragments * 2) + (lane & Int32(1))) * Int32(8) + + q + ) + csf_bases_packed = self.csf_reader.load_lane_bases_packed( + w13_sfb.iterator, + section_expert, + physical_tile, + csf_r0, + row_stride=16, + n_fragments=self.n_fragments, + ) + if cutlass.const_expr(self.tile_n == 128 and self.n64_tail): + if physical_tile == Int32(self.n // 128): + csf_nr = Int32(64) + acc = tuple( cute.make_rmem_tensor((4,), cutlass.Float32) for _ in range(self.n_fragments) @@ -695,34 +723,42 @@ def _run_task( expert, projection_tile, next_slice, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, l2_policy, ) cute.arch.cp_async_commit_group() if cutlass.const_expr(self.max_copy_groups == 2): cute.arch.cp_async_wait_group(1) cute.arch.sync_threads() + asc = ld_shared_u32(input_stage_base + Int32(self.sfa_offset)) if cutlass.const_expr(self.csf_inline): - self.csf_reader.expand_slots( - w13_sfb.iterator, sfb_base, tid, self.threads_per_cta, 1 - ) - cute.arch.sync_threads() - if cutlass.const_expr(self.tile_n == 64): - sfb_base += ( - projection_tile % Int32(self.n_tiles) & Int32(1) - ) * Int32(256) - for nt in cutlass.range_constexpr(self.n_fragments): - n8 = ( - warp * Int32(self.n_fragments * 2) - + Int32(nt * 2) - + (lane & Int32(1)) - ) - b_scale_words[nt] = ld_shared_u32( - sfb_base + ((n8 * Int32(8) + q) << Int32(2)) + self.csf_reader.decode_compact_1bit_words( + w13_sfb.iterator, + sfb_base, + csf_bounds_smem, + k128_slice, + csf_bases_packed, + csf_r0, + b_scale_words, + row_stride=16, + n_fragments=self.n_fragments, + half_offset=csf_half_offset + if cutlass.const_expr(self.tile_n == 64) + else None, + nr=csf_nr + if cutlass.const_expr(self.tile_n == 128 and self.n64_tail) + else None, ) - asc = ld_shared_u32(input_stage_base + Int32(self.sfa_offset)) + else: + for nt in cutlass.range_constexpr(self.n_fragments): + n8 = ( + warp * Int32(self.n_fragments * 2) + + Int32(nt * 2) + + (lane & Int32(1)) + ) + b_scale_words[nt] = ld_shared_u32( + sfb_base + ((n8 * Int32(8) + q) << Int32(2)) + ) for kb in cutlass.range_constexpr(4): # One activation is repeated across the eight hardware columns. a_src = ( @@ -781,9 +817,7 @@ def _run_task( expert, projection_tile, next_slice, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, l2_policy, ) cute.arch.cp_async_commit_group() @@ -1308,9 +1342,13 @@ def __init__( # Weight ring per projection group (up = group 0, gate = group 1). self.b_payload_bytes = self.tile_n * self.tile_k // 2 - self.sfb_bytes = 512 if self.csf_inline else self.tile_n * 4 + self.sfb_bytes = COMPACT_1BIT_SLOT_BYTES if self.csf_inline else self.tile_n * 4 self.weight_stage_bytes = self.b_payload_bytes + self.sfb_bytes - self.weight_ring_bytes = self.stages * self.weight_stage_bytes + self.csf_bounds_offset = self.stages * self.weight_stage_bytes + self.csf_bounds_bytes = ( + (((self.k // 128) * 8 + 8 + 255) // 256) * 256 if self.csf_inline else 0 + ) + self.weight_ring_bytes = self.csf_bounds_offset + self.csf_bounds_bytes self.total_smem_bytes = max( self.input_ring_bytes + 2 * self.weight_ring_bytes, 8 * 2 * self.tile_n * 2, @@ -1466,9 +1504,8 @@ def _stage_n64_sfb( k128_slice: Int32, local_tid: Int32, l2_policy, - bounds=None, - value_offset=None, - base_word=None, + bounds_smem=None, + prefetch_bounds: cutlass.Constexpr = False, ): physical_tile = output_tile // Int32(128 // self.tile_n) packed_half = output_tile % Int32(128 // self.tile_n) @@ -1476,39 +1513,51 @@ def _stage_n64_sfb( if physical_tile == Int32(self.n // 128): n_rows = Int32(64) if cutlass.const_expr(self.csf_inline): - if local_tid < Int32(32): - target = cute.make_ptr( - cutlass.Uint8, dst_base, cute.AddressSpace.smem, assumed_align=16 - ) - group = ( - projection * Int32(self.csf_reader.plane.storage.groups) - + physical_tile * Int32(self.csf_reader.plane.storage.column_groups) - + k128_slice + half_arg = packed_half if cutlass.const_expr(self.tile_n == 64) else None + if cutlass.const_expr(prefetch_bounds): + if local_tid < Int32(32): + self.csf_reader.stage_compact_1bit_codes( + scales.iterator, + expert_idx, + dst_base, + local_tid, + (projection, physical_tile, k128_slice), + half_idx=half_arg, + l2_policy=l2_policy, + ) + section_expert = ( + expert_idx * Int32(self.csf_reader.plane.sections) + projection ) - cached = None - if cutlass.const_expr(bounds is not None): - first, end = Uint32(0), Uint32(0) - for chunk in cutlass.range_constexpr(cute.size(bounds, mode=[0])): - selected_first = cute.arch.shuffle_sync( - bounds[chunk, 0], k128_slice % Int32(32) - ) - selected_end = cute.arch.shuffle_sync( - bounds[chunk, 1], k128_slice % Int32(32) - ) - if k128_slice // Int32(32) == Int32(chunk): - first, end = selected_first, selected_end - cached = (first, end) - self.csf_reader.stage_compressed( + self.csf_reader.prefetch_column_bounds_smem( scales.iterator, - expert_idx, - group, - target, + section_expert, + physical_tile, + bounds_smem, local_tid, - cached, - value_offset, - base_word, - coordinates=(projection, physical_tile, k128_slice), + num_threads=64, + sync_warp_after=True, ) + if local_tid < Int32(32): + self.csf_reader.stage_compact_1bit_exceptions( + scales.iterator, + dst_base, + local_tid, + k128_slice, + bounds_smem=bounds_smem, + l2_policy=l2_policy, + ) + else: + if local_tid < Int32(32): + self.csf_reader.stage_compact_1bit( + scales.iterator, + expert_idx, + dst_base, + local_tid, + (projection, physical_tile, k128_slice), + bounds_smem=bounds_smem, + half_idx=half_arg, + l2_policy=l2_policy, + ) return if local_tid < Int32(self.tile_n // 4): dst_addr = dst_base + (local_tid << Int32(4)) @@ -1555,9 +1604,8 @@ def _stage_slice( output_tile: Int32, k128_slice: Int32, l2_policy, - csf_bounds=None, - csf_value_offset=None, - csf_base_word=None, + csf_bounds_smem=None, + prefetch_bounds: cutlass.Constexpr = False, ): stage_idx = Int32(0) if cutlass.const_expr(self.stages == 2): @@ -1614,9 +1662,8 @@ def _stage_slice( k128_slice, local_tid, l2_policy, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, + prefetch_bounds=prefetch_bounds, ) else: packed_tile = projection_tile // Int32(2) @@ -1808,19 +1855,11 @@ def _run_task( if q_in >= group_count: q_in = Int32(0) - csf_bounds, csf_base_word, csf_value_offset = None, None, None - if cutlass.const_expr(self.csf_inline): - physical_tile = output_tile // Int32(128 // self.tile_n) - section_expert = expert * Int32(self.csf_reader.plane.sections) + group - csf_value_offset = self.csf_reader.plane.group_value_offset( - w13_sfb.iterator - ) - csf_bounds = self.csf_reader.prefetch_column_bounds( - w13_sfb.iterator, section_expert, physical_tile - ) - csf_base_word = self.csf_reader.prefetch_row_bases( - w13_sfb.iterator, section_expert, physical_tile, local_tid - ) + csf_bounds_smem = ( + weight_ring_base + Int32(self.csf_bounds_offset) + if cutlass.const_expr(self.csf_inline) + else None + ) if cutlass.const_expr(0 < self.k // 128): self._stage_slice( @@ -1842,12 +1881,36 @@ def _run_task( output_tile, Int32(0), l2_policy, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, + prefetch_bounds=True, ) cute.arch.cp_async_commit_group() + csf_bases_packed = None + csf_r0, csf_half_offset, csf_nr = Int32(0), Int32(0), Int32(128) + if cutlass.const_expr(self.csf_inline): + physical_tile = output_tile // Int32(128 // self.tile_n) + packed_half = output_tile % Int32(128 // self.tile_n) + section_expert = expert * Int32(self.csf_reader.plane.sections) + group + csf_half_offset = packed_half * Int32(self.tile_n) + csf_r0 = ( + csf_half_offset + + (local_warp * Int32(self.n_fragments * 2) + (lane & Int32(1))) + * Int32(8) + + q + ) + csf_bases_packed = self.csf_reader.load_lane_bases_packed( + w13_sfb.iterator, + section_expert, + physical_tile, + csf_r0, + row_stride=16, + n_fragments=self.n_fragments, + ) + if cutlass.const_expr(self.tile_n == 128 and self.n64_tail): + if physical_tile == Int32(self.n // 128): + csf_nr = Int32(64) + for nt in cutlass.range_constexpr(self.n_fragments): acc[nt].fill(0.0) b_scale_words.fill(Uint32(0)) @@ -1887,38 +1950,43 @@ def _run_task( output_tile, next_slice, l2_policy, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, ) cute.arch.cp_async_commit_group() if cutlass.const_expr(self.max_copy_groups == 2): cute.arch.cp_async_wait_group(1) cute.arch.sync_threads() + asc = ld_shared_u32( + input_stage + Int32(self.input_sfa_offset) + (q_in << Int32(2)) + ) if cutlass.const_expr(self.csf_inline): - self.csf_reader.expand_slots( + self.csf_reader.decode_compact_1bit_words( w13_sfb.iterator, sfb_base, - local_tid, - self.threads_per_group, - 1, - ) - cute.arch.sync_threads() - if cutlass.const_expr(self.tile_n == 64): - sfb_base += (output_tile & Int32(1)) * Int32(256) - - for nt in cutlass.range_constexpr(self.n_fragments): - n8 = ( - local_warp * Int32(self.n_fragments * 2) - + Int32(nt * 2) - + (lane & Int32(1)) - ) - b_scale_words[nt] = ld_shared_u32( - sfb_base + ((n8 * Int32(8) + q) << Int32(2)) + csf_bounds_smem, + k128_slice, + csf_bases_packed, + csf_r0, + b_scale_words, + row_stride=16, + n_fragments=self.n_fragments, + half_offset=csf_half_offset + if cutlass.const_expr(self.tile_n == 64) + else None, + nr=csf_nr + if cutlass.const_expr(self.tile_n == 128 and self.n64_tail) + else None, ) - asc = ld_shared_u32( - input_stage + Int32(self.input_sfa_offset) + (q_in << Int32(2)) - ) + else: + for nt in cutlass.range_constexpr(self.n_fragments): + n8 = ( + local_warp * Int32(self.n_fragments * 2) + + Int32(nt * 2) + + (lane & Int32(1)) + ) + b_scale_words[nt] = ld_shared_u32( + sfb_base + ((n8 * Int32(8) + q) << Int32(2)) + ) for kb in cutlass.range_constexpr(4): phys_vec = (Int32(kb * 2) + (c >> Int32(1))) ^ q_in a_src = ( @@ -1984,9 +2052,7 @@ def _run_task( output_tile, next_slice, l2_policy, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, ) cute.arch.cp_async_commit_group() k128_slice += Int32(1) @@ -2212,10 +2278,18 @@ def __init__( self.b_stage_bytes = self.tile_n * self.tile_k // 2 self.b_storage_bytes = self.stages * self.b_stage_bytes self.sfb_storage_offset = self.b_storage_offset + self.b_storage_bytes - self.sfb_stage_bytes = 512 + self.sfb_stage_bytes = ( + COMPACT_1BIT_SLOT_BYTES if (self.csf_inline and self.n64_tail) else 512 + ) self.shared_bytes = self.sfb_storage_offset + self.stages * self.sfb_stage_bytes + self.csf_bounds_offset = ((self.shared_bytes + 255) // 256) * 256 + self.csf_bounds_bytes = ( + (((self.intermediate_tiles * 8 + 8 + 255) // 256) * 256) + if (self.csf_inline and self.n64_tail) + else 0 + ) self.shared_words = (self.shared_bytes + 3) // 4 - self.region_words = self.shared_words + (128 if self.csf_inline else 0) + self.region_words = (self.csf_bounds_offset + self.csf_bounds_bytes + 3) // 4 @cute.jit def __call__( @@ -2302,44 +2376,48 @@ def _stage_n64_sfb( k128_slice: Int32, tid: Int32, l2_policy, - bounds=None, - value_offset=None, - base_word=None, + bounds_smem=None, + prefetch_bounds: cutlass.Constexpr = False, ): total_k32 = self.n // 32 if cutlass.const_expr(self.csf_inline): if tid < Int32(32): - target = cute.make_ptr( - cutlass.Uint8, dst_base, cute.AddressSpace.smem, assumed_align=16 - ) - group = ( - output_tile * Int32(self.csf_reader.plane.storage.column_groups) - + k128_slice - ) - cached = None - if cutlass.const_expr(bounds is not None): - first, end = Uint32(0), Uint32(0) - for chunk in cutlass.range_constexpr(cute.size(bounds, mode=[0])): - selected_first = cute.arch.shuffle_sync( - bounds[chunk, 0], k128_slice % Int32(32) - ) - selected_end = cute.arch.shuffle_sync( - bounds[chunk, 1], k128_slice % Int32(32) - ) - if k128_slice // Int32(32) == Int32(chunk): - first, end = selected_first, selected_end - cached = (first, end) - self.csf_reader.stage_compressed( - scales.iterator, - expert_idx, - group, - target, - tid, - cached, - value_offset, - base_word, - coordinates=(Int32(0), output_tile, k128_slice), - ) + if cutlass.const_expr(prefetch_bounds): + self.csf_reader.stage_compact_1bit_codes( + scales.iterator, + expert_idx, + dst_base, + tid, + (Int32(0), output_tile, k128_slice), + l2_policy=l2_policy, + ) + self.csf_reader.prefetch_column_bounds_smem( + scales.iterator, + expert_idx, + output_tile, + bounds_smem, + tid, + num_threads=32, + sync_warp_after=True, + ) + self.csf_reader.stage_compact_1bit_exceptions( + scales.iterator, + dst_base, + tid, + k128_slice, + bounds_smem=bounds_smem, + l2_policy=l2_policy, + ) + else: + self.csf_reader.stage_compact_1bit( + scales.iterator, + expert_idx, + dst_base, + tid, + (Int32(0), output_tile, k128_slice), + bounds_smem=bounds_smem, + l2_policy=l2_policy, + ) return scales_u8 = cute.recast_tensor(scales, cutlass.Uint8) expert_bytes = self.k * total_k32 @@ -2379,9 +2457,8 @@ def _stage_slice( output_tile: Int32, intermediate_slice: Int32, l2_policy, - csf_bounds=None, - csf_value_offset=None, - csf_base_word=None, + csf_bounds_smem=None, + prefetch_bounds: cutlass.Constexpr = False, ): stage = intermediate_slice & Int32(1) a_base = smem_base + stage * Int32(self.a_stage_bytes) @@ -2438,9 +2515,8 @@ def _stage_slice( intermediate_slice, tid, l2_policy, - csf_bounds, - csf_value_offset, - csf_base_word, + csf_bounds_smem, + prefetch_bounds=prefetch_bounds, ) else: packed_tile = output_tile // Int32(2) @@ -2591,18 +2667,6 @@ def _run_task( if q_in >= group_count: q_in = Int32(0) - csf_bounds, csf_base_word, csf_value_offset = None, None, None - if cutlass.const_expr(self.csf_inline and self.n64_tail): - csf_value_offset = self.csf_reader.plane.group_value_offset( - down_sfb_rp.iterator - ) - csf_bounds = self.csf_reader.prefetch_column_bounds( - down_sfb_rp.iterator, expert_idx, output_tile - ) - csf_base_word = self.csf_reader.prefetch_row_bases( - down_sfb_rp.iterator, expert_idx, output_tile, tid - ) - self._stage_slice( intermediate_u32, down_rp, @@ -2616,14 +2680,28 @@ def _run_task( output_tile, Int32(0), l2_policy, - csf_bounds, - csf_value_offset, - csf_base_word, + smem_base + Int32(self.csf_bounds_offset) + if cutlass.const_expr(self.csf_inline and self.n64_tail) + else None, + prefetch_bounds=True, ) cute.arch.cp_async_commit_group() + csf_bases_packed = None + if cutlass.const_expr(self.csf_inline and self.n64_tail): + csf_bases_packed = self.csf_reader.load_lane_bases_packed( + down_sfb_rp.iterator, + expert_idx, + output_tile, + (warp_idx * Int32(4) + (lane & Int32(1))) * Int32(8) + q, + row_stride=16, + n_fragments=2, + ) + for nt in cutlass.range_constexpr(2): facc[nt].fill(0.0) + sfb_reg = cute.make_rmem_tensor((2,), Uint32) + sfb_reg.fill(Uint32(0)) intermediate_slice = Int32(0) while intermediate_slice < Int32(self.intermediate_tiles): @@ -2655,22 +2733,34 @@ def _run_task( output_tile, next_slice, l2_policy, - csf_bounds, - csf_value_offset, - csf_base_word, + smem_base + Int32(self.csf_bounds_offset) + if cutlass.const_expr(self.csf_inline and self.n64_tail) + else None, ) cute.arch.cp_async_commit_group() cute.arch.cp_async_wait_group(1) cute.arch.fence_proxy("async.shared", space="cta") cute.arch.sync_threads() - sfb_words = sfb_base - if cutlass.const_expr(self.csf_inline): - sfb_words = smem_base + Int32(self.shared_words * 4) - self.csf_reader.expand_warp_rows( - down_sfb_rp.iterator, sfb_base, sfb_words, warp_idx, lane - ) asc = ld_shared_u32(sfa_base + (q_in << Int32(2))) + if cutlass.const_expr(self.csf_inline and self.n64_tail): + self.csf_reader.decode_compact_1bit_words( + down_sfb_rp.iterator, + sfb_base, + smem_base + Int32(self.csf_bounds_offset), + intermediate_slice, + csf_bases_packed, + (warp_idx * Int32(4) + (lane & Int32(1))) * Int32(8) + q, + sfb_reg, + row_stride=16, + n_fragments=2, + ) + else: + for nt in cutlass.range_constexpr(2): + n8 = warp_idx * Int32(4) + Int32(nt * 2) + (lane & Int32(1)) + sfb_reg[nt] = ld_shared_u32( + sfb_base + ((n8 * Int32(8) + q) << Int32(2)) + ) for kb in cutlass.range_constexpr(4): u_phys = (Int32(kb * 2) + (c >> Int32(1))) ^ q_in @@ -2694,10 +2784,7 @@ def _run_task( dn_b0[nt] = wb0 dn_b1[nt] = wb1 for nt in cutlass.range_constexpr(2): - n8 = warp_idx * Int32(4) + Int32(nt * 2) + (lane & Int32(1)) - sfb_word = ld_shared_u32( - sfb_words + ((n8 * Int32(8) + q) << Int32(2)) - ) + sfb_word = sfb_reg[nt] fragment = facc[nt] d0, d1, d2, d3 = mxfp8_mma_m16n8k32_f32_e2m1_e4m3( fragment[0], diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py index 981a24f0308..850c341b233 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py @@ -159,9 +159,9 @@ def __init__( self.a_payload_bytes = self.tile_m * self.a_row_stride self.a_scale_bytes = self.tile_m * 4 self.b_payload_bytes = self.tile_n * self.tile_k // 2 - # Always reserve 512 B per projection SFB slot even when tile_n == 64, - # because inline CSF attaches post-__init__ and expands 128-row tiles. - self.sfb_bytes = 512 if self.tile_n == 64 else (self.tile_n // 8) * 8 * 4 + # Compact 1-bit inline CSF uses a 256 B aligned slot, which fits inside both + # 256 B (tile_n=64) and 512 B (tile_n=128) SFB stage buffers. + self.sfb_bytes = (self.tile_n // 8) * 8 * 4 self.a_offset = 0 self.sfa_offset = self.a_offset + self.a_payload_bytes self.gate_b_offset = self.sfa_offset + self.a_scale_bytes @@ -180,11 +180,6 @@ def __init__( if self.use_tok_smem else self.shared_bytes ) - self.csf_warp_scratch_offset = ((total_shared_bytes + 15) // 16) * 16 - if self.fast_m128_src and self.tile_n == 64: - # 512 B warp-private scratch (128 B/warp) for lock-free inline CSF - # reconstruction when csf_inline attaches post-__init__. - total_shared_bytes = self.csf_warp_scratch_offset + self.num_warps * 128 self.slot_smem_offset = ((total_shared_bytes + 15) // 16) * 16 if self.fast_m128_src: total_shared_bytes = self.slot_smem_offset + 16 @@ -216,6 +211,24 @@ def __init__( if not self.trellis_direct_lut: self.shared_words = (self.shared_bytes + 4096 + 3) // 4 + @property + def _csf_gate_bounds_offset(self) -> int: + return ((self.shared_words * 4 + 15) // 16) * 16 + + @property + def _csf_up_bounds_offset(self) -> int: + return self._csf_gate_bounds_offset + self.csf_reader.compact_1bit_bounds_bytes + + @property + def _region_words(self) -> int: + if self.csf_inline: + return ( + self._csf_up_bounds_offset + + self.csf_reader.compact_1bit_bounds_bytes + + 3 + ) // 4 + return self.shared_words + @cute.jit def __call__( self, @@ -434,15 +447,13 @@ def _stage_n64_sfb( scales: cute.Tensor, dst_base: Int32, expert_idx: Int32, - projection: Int32, + projection: cutlass.Constexpr[int], output_tile: Int32, k128_slice: Int32, intermediate_tiles: Int32, total_k32: cutlass.Constexpr, tid: Int32, - bounds=None, - value_offset=None, - base_word=None, + bounds_smem=None, ): physical_tile = ( output_tile >> Int32(1) @@ -455,38 +466,23 @@ def _stage_n64_sfb( else Int32(0) ) if cutlass.const_expr(self.csf_inline): - if tid < Int32(32): - group = ( - projection * Int32(self.csf_reader.plane.storage.groups) - + physical_tile * Int32(self.csf_reader.plane.storage.column_groups) - + k128_slice - ) - target = cute.make_ptr( - cutlass.Uint8, dst_base, cute.AddressSpace.smem, assumed_align=16 - ) - cached = None - if cutlass.const_expr(bounds is not None): - first, end = Uint32(0), Uint32(0) - for chunk in cutlass.range_constexpr(cute.size(bounds, mode=[0])): - selected_first = cute.arch.shuffle_sync( - bounds[chunk, 0], k128_slice % Int32(32) - ) - selected_end = cute.arch.shuffle_sync( - bounds[chunk, 1], k128_slice % Int32(32) - ) - if k128_slice // Int32(32) == Int32(chunk): - first, end = selected_first, selected_end - cached = (first, end) - self.csf_reader.stage_compressed( + # Run gate (projection=1) on warp 0 and up (projection=0) on warp 1 in parallel. + prod_lane = tid if cutlass.const_expr(projection == 1) else tid - Int32(32) + is_prod = ( + tid < Int32(32) + if cutlass.const_expr(projection == 1) + else (tid >= Int32(32) and tid < Int32(64)) + ) + half_arg = packed_half if cutlass.const_expr(self.tile_n == 64) else None + if is_prod: + self.csf_reader.stage_compact_1bit( scales.iterator, expert_idx, - group, - target, - tid, - cached, - value_offset, - base_word, - (projection, physical_tile, k128_slice), + dst_base, + prod_lane, + (Int32(projection), physical_tile, k128_slice), + bounds_smem=bounds_smem, + half_idx=half_arg, ) else: logical_n = intermediate_tiles * Int32(128) @@ -561,11 +557,7 @@ def _stage_slice( input_k128_tiles: Int32, intermediate_tiles: Int32, packed_w13_tiles: Int32, - gate_bounds=None, - up_bounds=None, - csf_value_offset=None, - gate_base_word=None, - up_base_word=None, + gate_bounds_smem=None, stage_m: cutlass.Constexpr[int] = 0, stage_idx: Int32 | None = None, mbar_base=None, @@ -742,34 +734,54 @@ def _stage_slice( l2_policy, ) if (not self.csf_inline and not self.fast_m128_src) or k_half == Int32(0): - self._stage_n64_sfb( - w13_sfb_rp, - gate_sfb_base, - expert_idx, - Int32(1), - output_tile, - k128_slice, - intermediate_tiles, - total_k32, - tid, - gate_bounds, - csf_value_offset, - gate_base_word, - ) - self._stage_n64_sfb( - w13_sfb_rp, - up_sfb_base, - expert_idx, - Int32(0), - output_tile, - k128_slice, - intermediate_tiles, - total_k32, - tid, - up_bounds, - csf_value_offset, - up_base_word, - ) + if cutlass.const_expr(self.csf_inline): + # Warp 0 stages gate (section=1) and warp 1 stages up (section=0) + # in a single unified path so stage_compact_1bit is emitted once. + if tid < Int32(64): + is_up = tid >> Int32(5) + physical_tile = ( + output_tile >> Int32(1) + if cutlass.const_expr(self.tile_n == 64) + else output_tile + ) + half_arg = ( + output_tile & Int32(1) + if cutlass.const_expr(self.tile_n == 64) + else None + ) + self.csf_reader.stage_compact_1bit( + w13_sfb_rp.iterator, + expert_idx, + gate_sfb_base + is_up * Int32(self.sfb_bytes), + tid & Int32(31), + (Int32(1) - is_up, physical_tile, k128_slice), + bounds_smem=gate_bounds_smem + + is_up * Int32(self.csf_reader.compact_1bit_bounds_bytes), + half_idx=half_arg, + ) + else: + self._stage_n64_sfb( + w13_sfb_rp, + gate_sfb_base, + expert_idx, + 1, + output_tile, + k128_slice, + intermediate_tiles, + total_k32, + tid, + ) + self._stage_n64_sfb( + w13_sfb_rp, + up_sfb_base, + expert_idx, + 0, + output_tile, + k128_slice, + intermediate_tiles, + total_k32, + tid, + ) else: self._stage_b_half_k64( w13_rp, @@ -877,9 +889,9 @@ def _run_task( if cutlass.const_expr(self.trellis_direct_lut): trellis_lut_addr = trellis_lut.iterator.toint() - gate_bounds, up_bounds = None, None - gate_base_word, up_base_word = None, None - csf_value_offset = None + gate_bounds_smem = None + csf_pair_bases, csf_gate_bases, csf_up_bases = None, None, None + csf_nr = Int32(128) cache_k128_scales = self.fast_m128_src and not self.w4a8_trellis is_m128_n64 = self.tile_m == 128 and self.tile_n == 64 is_m128_n128 = self.tile_m == 128 and self.tile_n == 128 and self.num_warps == 8 @@ -904,6 +916,33 @@ def _run_task( l2_policy = None if cutlass.const_expr(self.use_l2_evict_b): l2_policy = create_l2_evict_first_policy() + gate_bounds_smem = ( + smem_base + Int32(self._csf_gate_bounds_offset) + if cutlass.const_expr(self.csf_inline) + else None + ) + if cutlass.const_expr(self.csf_inline): + # All 128 threads cooperatively prefetch gate (warps 0+2) and up + # (warps 1+3) column bounds in a single divergence-free call. + # When use_tok_smem is set this shares its sync_threads(). + section_expert_pf = expert_idx * Int32(self.csf_reader.plane.sections) + csf_tile_pf = ( + output_tile >> Int32(1) + if cutlass.const_expr(self.tile_n == 64) + else output_tile + ) + is_up_pf = (tid >> Int32(5)) & Int32(1) + coop_tid = ((tid >> Int32(6)) << Int32(5)) + (tid & Int32(31)) + self.csf_reader.prefetch_column_bounds_smem( + w13_sfb_rp.iterator, + section_expert_pf + (Int32(1) - is_up_pf), + csf_tile_pf, + gate_bounds_smem + + is_up_pf * Int32(self.csf_reader.compact_1bit_bounds_bytes), + coop_tid, + num_threads=64, + sync_warp_after=not self.use_tok_smem, + ) if cutlass.const_expr(self.use_tok_smem): tok_smem_base = smem_base + Int32(self.tok_smem_offset) physical_row_base_init = Int64(source_m_tile) * Int64( @@ -917,33 +956,6 @@ def _run_task( tok_init = tok_init // Int32(self.num_topk) st_shared_u32(tok_smem_base + (tid << Int32(2)), Uint32(tok_init)) cute.arch.sync_threads() - if cutlass.const_expr(self.csf_inline): - # A task holds its expert and output row group across the K sweep. - # Fetch each column group's dependent global bounds once, then - # select fixed register fields through producer-warp shuffles. - section_expert = expert_idx * Int32(self.csf_reader.plane.sections) - csf_output_tile = ( - output_tile >> Int32(1) - if cutlass.const_expr(self.tile_n == 64) - else output_tile - ) - # The exception value plane is shared by every expert and K tile. - csf_value_offset = self.csf_reader.plane.group_value_offset( - w13_sfb_rp.iterator - ) - gate_bounds = self.csf_reader.prefetch_column_bounds( - w13_sfb_rp.iterator, section_expert + Int32(1), csf_output_tile - ) - up_bounds = self.csf_reader.prefetch_column_bounds( - w13_sfb_rp.iterator, section_expert, csf_output_tile - ) - # Row bases are invariant across the column groups staged by a task. - gate_base_word = self.csf_reader.prefetch_row_bases( - w13_sfb_rp.iterator, section_expert + Int32(1), csf_output_tile, tid - ) - up_base_word = self.csf_reader.prefetch_row_bases( - w13_sfb_rp.iterator, section_expert, csf_output_tile, tid - ) input_k64_tiles = input_k128_tiles * Int32(2) no_tail_barrier = self.stages >= 3 @@ -968,11 +980,7 @@ def _run_task( input_k128_tiles, intermediate_tiles, packed_w13_tiles, - gate_bounds, - up_bounds, - csf_value_offset, - gate_base_word, - up_base_word, + gate_bounds_smem, stage_m=compute_m, stage_idx=Int32(preload_slice), mbar_base=mbar_base, @@ -980,6 +988,58 @@ def _run_task( ) cute.arch.cp_async_commit_group() + if cutlass.const_expr(self.csf_inline): + # Overlap invariant base loads with committed preload A[0]+B[0]+codes[0]. + section_expert = expert_idx * Int32(self.csf_reader.plane.sections) + csf_output_tile = ( + output_tile >> Int32(1) + if cutlass.const_expr(self.tile_n == 64) + else output_tile + ) + if cutlass.const_expr(self.tile_n == 64): + csf_pair_bases = self.csf_reader.load_lane_pair_bases_packed( + w13_sfb_rp.iterator, + section_expert + Int32(1), + section_expert, + csf_output_tile, + ((output_tile & Int32(1)) << Int32(6)) + (warp_n << Int32(4)) + q, + row_stride=8, + ) + elif cutlass.const_expr(transpose_grouped): + csf_r0 = (warp_n * Int32(4) + (lane & Int32(1))) * Int32(8) + q + csf_pair_bases = self.csf_reader.load_lane_pair_bases_packed( + w13_sfb_rp.iterator, + section_expert + Int32(1), + section_expert, + csf_output_tile, + csf_r0, + row_stride=16, + ) + if cutlass.const_expr(self.n64_tail): + if csf_output_tile == intermediate_tiles - Int32(1): + csf_nr = Int32(64) + else: + csf_r0 = (warp_n << Int32(5)) + q + csf_gate_bases = self.csf_reader.load_lane_bases_packed( + w13_sfb_rp.iterator, + section_expert + Int32(1), + csf_output_tile, + csf_r0, + row_stride=8, + n_fragments=4, + ) + csf_up_bases = self.csf_reader.load_lane_bases_packed( + w13_sfb_rp.iterator, + section_expert, + csf_output_tile, + csf_r0, + row_stride=8, + n_fragments=4, + ) + if cutlass.const_expr(self.n64_tail): + if csf_output_tile == intermediate_tiles - Int32(1): + csf_nr = Int32(64) + # Keep each MMA's four accumulator registers as an independent # fragment. A mutable M-fragment tuple avoids packing and unpacking # the complete live accumulator set around loop-carried values even @@ -1045,11 +1105,7 @@ def _run_task( input_k128_tiles, intermediate_tiles, packed_w13_tiles, - gate_bounds, - up_bounds, - csf_value_offset, - gate_base_word, - up_base_word, + gate_bounds_smem, stage_m=compute_m, stage_idx=next_stage, mbar_base=mbar_base, @@ -1059,61 +1115,106 @@ def _run_task( cute.arch.cp_async_wait_group(preload_slices) cute.arch.sync_threads() - if cutlass.const_expr(cache_sfb): - if k64_slice & Int32(1) == Int32(0): - if cutlass.const_expr( - self.csf_inline - and is_m128_n64 - and self.csf_reader.plane.destination == 3 - and self.csf_reader.plane.storage.bits == 1 - and self.csf_reader.plane.columns % 4 == 0 - ): - warp_sfb_scratch = ( - smem_base - + Int32(self.csf_warp_scratch_offset) - + (warp_idx << Int32(7)) - ) - self.csf_reader.expand_warp_half_pair( - w13_sfb_rp.iterator, - gate_sfb_base, - up_sfb_base, - warp_sfb_scratch, - output_tile & Int32(1), - warp_idx, - lane, - csf_value_offset, - ) - gate_scale_words[0] = ld_shared_u32( - warp_sfb_scratch + (q << Int32(2)) - ) - gate_scale_words[1] = ld_shared_u32( - warp_sfb_scratch + ((q + Int32(8)) << Int32(2)) - ) - up_scale_words[0] = ld_shared_u32( - warp_sfb_scratch + Int32(64) + (q << Int32(2)) - ) - up_scale_words[1] = ld_shared_u32( - warp_sfb_scratch + Int32(64) + ((q + Int32(8)) << Int32(2)) - ) - else: + scale_shift = Uint32(k64_slice & Int32(1)) * Uint32(16) + if not skip_tail_mma: + if cutlass.const_expr(cache_sfb): + if k64_slice & Int32(1) == Int32(0): if cutlass.const_expr(self.csf_inline): - self.csf_reader.expand_slots( - w13_sfb_rp.iterator, - gate_sfb_base, - tid, - self.threads_per_cta, - 2, - ) - cute.arch.sync_threads() - # One native K128 word serves both K64 pipeline epochs. - if not skip_tail_mma: + k128_slice_cur = k64_slice >> Int32(1) + if cutlass.const_expr(self.tile_n == 64): + self.csf_reader.decode_compact_1bit_pair_words( + w13_sfb_rp.iterator, + gate_sfb_base, + up_sfb_base, + gate_bounds_smem, + k128_slice_cur, + csf_pair_bases, + (warp_n << Int32(4)) + q, + (output_tile & Int32(1)) << Int32(6), + gate_scale_words, + up_scale_words, + ) + elif cutlass.const_expr(transpose_grouped): + up_bounds_cur = gate_bounds_smem + Int32( + self.csf_reader.compact_1bit_bounds_bytes + ) + r0_cur = ( + warp_n * Int32(4) + (lane & Int32(1)) + ) * Int32(8) + q + self.csf_reader.decode_compact_1bit_words( + w13_sfb_rp.iterator, + gate_sfb_base, + gate_bounds_smem, + k128_slice_cur, + csf_pair_bases, + r0_cur, + gate_scale_words, + row_stride=16, + n_fragments=2, + nr=csf_nr + if cutlass.const_expr(self.n64_tail) + else None, + base_byte_offset=0, + hoist_bounds=False, + ) + self.csf_reader.decode_compact_1bit_words( + w13_sfb_rp.iterator, + up_sfb_base, + up_bounds_cur, + k128_slice_cur, + csf_pair_bases, + r0_cur, + up_scale_words, + row_stride=16, + n_fragments=2, + nr=csf_nr + if cutlass.const_expr(self.n64_tail) + else None, + base_byte_offset=2, + hoist_bounds=False, + ) + else: + up_bounds_cur = gate_bounds_smem + Int32( + self.csf_reader.compact_1bit_bounds_bytes + ) + r0_cur = (warp_n << Int32(5)) + q + self.csf_reader.decode_compact_1bit_words( + w13_sfb_rp.iterator, + gate_sfb_base, + gate_bounds_smem, + k128_slice_cur, + csf_gate_bases, + r0_cur, + gate_scale_words, + row_stride=8, + n_fragments=4, + nr=csf_nr + if cutlass.const_expr(self.n64_tail) + else None, + aligned_v4_codes=True, + hoist_bounds=self.tile_m != 16, + ) + self.csf_reader.decode_compact_1bit_words( + w13_sfb_rp.iterator, + up_sfb_base, + up_bounds_cur, + k128_slice_cur, + csf_up_bases, + r0_cur, + up_scale_words, + row_stride=8, + n_fragments=4, + nr=csf_nr + if cutlass.const_expr(self.n64_tail) + else None, + aligned_v4_codes=True, + hoist_bounds=self.tile_m != 16, + ) + else: + # One native K128 word serves both K64 pipeline epochs. for nt in cutlass.range_constexpr(n_fragments): n8 = warp_n * Int32(n_fragments) + Int32(nt) - if cutlass.const_expr( - self.tile_n == 64 and self.csf_inline - ): - n8 = (output_tile & Int32(1)) * Int32(8) + n8 - elif cutlass.const_expr(transpose_grouped): + if cutlass.const_expr(transpose_grouped): n8 = ( warp_n * Int32(4) + Int32(nt * 2) @@ -1126,8 +1227,6 @@ def _run_task( up_scale_words[nt] = ld_shared_u32( up_sfb_base + scale_offset ) - scale_shift = Uint32(k64_slice & Int32(1)) * Uint32(16) - if not skip_tail_mma: if cutlass.const_expr(cache_k128_scales): if k64_slice & Int32(1) == Int32(0): for blk in cutlass.range_constexpr(m_blocks): @@ -2043,7 +2142,7 @@ def kernel( @cute.struct class Storage: words: cute.struct.Align[ - cute.struct.MemRange[cutlass.Uint32, self.shared_words], + cute.struct.MemRange[cutlass.Uint32, self._region_words], 1024, ] diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py index 803a2ea8e9a..59c272a3a2c 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py @@ -43,6 +43,7 @@ from b12x._lib.intrinsics.mma import mxfp8_mma_m16n8k32_f32_e4m3 from b12x._lib.intrinsics.mma import mxfp8_mma_m16n8k32_f32_e2m1_e4m3 from b12x._lib.intrinsics.atomics import st_shared_u32 +from b12x._lib.quant.csf_inline import COMPACT_1BIT_SLOT_BYTES from b12x.moe._shared.kernels.w4a8_trellis_decode import ( _w4a8_stage_trellis_b_tile, _w4a8_trellis_lane_geom, @@ -174,10 +175,36 @@ def __init__( if not self.trellis_direct_lut: self.shared_words = (self.shared_bytes + 4096 + 3) // 4 + @property + def _csf_sfb_stage_bytes(self) -> int: + return COMPACT_1BIT_SLOT_BYTES if self.csf_inline else self.sfb_stage_bytes + + @property + def _csf_bounds_in_sfb(self) -> bool: + return ( + self.csf_inline + and self.csf_reader.compact_1bit_bounds_bytes + <= self.stages * (self.sfb_stage_bytes - COMPACT_1BIT_SLOT_BYTES) + ) + + @property + def _csf_bounds_offset(self) -> int: + if self._csf_bounds_in_sfb: + return self.sfb_storage_offset + self.stages * COMPACT_1BIT_SLOT_BYTES + return ((self.shared_words * 4 + 15) // 16) * 16 + @property def _region_words(self): - # Each warp reconstructs its scale rows outside the compressed pipeline slots. - return self.shared_words + (128 if self.csf_inline else 0) + # Pack column exception bounds inside the unused half of the SFB region + # whenever they fit (zero extra SMEM, exact 1024B multi-group alignment). + if self.csf_inline and not self._csf_bounds_in_sfb: + end_bytes = ( + self._csf_bounds_offset + self.csf_reader.compact_1bit_bounds_bytes + ) + if self.fused_groups > 1: + end_bytes = ((end_bytes + 1023) // 1024) * 1024 + return (end_bytes + 3) // 4 + return self.shared_words @cute.jit def __call__( @@ -308,9 +335,7 @@ def _stage_n64_sfb( total_output_tiles: Int32, total_k32: cutlass.Constexpr, tid: Int32, - bounds=None, - value_offset=None, - base_word=None, + bounds_smem=None, ): scales_u8 = cute.recast_tensor(scales, Uint8) total_output_n = total_output_tiles * Int32(128) @@ -322,38 +347,13 @@ def _stage_n64_sfb( tile_cols = Int32(2) if cutlass.const_expr(self.csf_inline): if tid < Int32(32): - target = cute.make_ptr( - Uint8, dst_base, cute.AddressSpace.smem, assumed_align=16 - ) - group = ( - output_tile * Int32(self.csf_reader.plane.storage.column_groups) - + k128_slice - ) - cached = None - coords = None - if cutlass.const_expr(bounds is not None): - first, end = Uint32(0), Uint32(0) - for chunk in cutlass.range_constexpr(cute.size(bounds, mode=[0])): - selected_first = cute.arch.shuffle_sync( - bounds[chunk, 0], k128_slice % Int32(32) - ) - selected_end = cute.arch.shuffle_sync( - bounds[chunk, 1], k128_slice % Int32(32) - ) - if k128_slice // Int32(32) == Int32(chunk): - first, end = selected_first, selected_end - cached = (first, end) - coords = (Int32(0), output_tile, k128_slice) - self.csf_reader.stage_compressed( + self.csf_reader.stage_compact_1bit( scales.iterator, expert_idx, - group, - target, + dst_base, tid, - cached, - value_offset, - base_word, - coords, + (Int32(0), output_tile, k128_slice), + bounds_smem=bounds_smem, ) if cutlass.const_expr(not self.csf_inline): source_base = ( @@ -396,7 +396,7 @@ def _stage_slice( stage_enabled = valid_rows > Int32(0) if not stage_enabled: word = tid - while word < Int32(self.shared_words): + while word < Int32(self._region_words): st_shared_u32(smem_base + word * Int32(4), Uint32(0)) word += Int32(self.threads_per_cta) if stage_enabled: @@ -411,30 +411,9 @@ def _stage_slice( sfb_base = ( smem_base + Int32(self.sfb_storage_offset) - + stage * Int32(self.sfb_stage_bytes) + + stage * Int32(self._csf_sfb_stage_bytes) ) - if cutlass.const_expr( - self.direct_routes - and self.csf_inline - and self.n64_repacked - and not self.w4a8_trellis - ): - total_output_tiles = packed_output_tiles * Int32(2) - total_k32 = intermediate_tiles * Int32(4) - if cutlass.const_expr(self.n64_tail): - total_k32 -= Int32(2) - self._stage_n64_sfb( - down_sfb_rp, - sfb_base, - expert_idx, - output_tile, - intermediate_slice, - total_output_tiles, - total_k32, - tid, - ) - words_per_row = intermediate_tiles * Int32(32) physical_row_base = source_m_tile * Int32( self.source_tile_m @@ -536,11 +515,10 @@ def _stage_slice( 8, ) elif cutlass.const_expr(self.n64_repacked): - if cutlass.const_expr(not (self.direct_routes and self.csf_inline)): - total_output_tiles = packed_output_tiles * Int32(2) - total_k32 = intermediate_tiles * Int32(4) - if cutlass.const_expr(self.n64_tail): - total_k32 -= Int32(2) + total_output_tiles = packed_output_tiles * Int32(2) + total_k32 = intermediate_tiles * Int32(4) + if cutlass.const_expr(self.n64_tail): + total_k32 -= Int32(2) self._stage_n64_b( down_rp, b_base, @@ -551,17 +529,19 @@ def _stage_slice( total_k32, tid, ) - if cutlass.const_expr(not (self.direct_routes and self.csf_inline)): - self._stage_n64_sfb( - down_sfb_rp, - sfb_base, - expert_idx, - output_tile, - intermediate_slice, - total_output_tiles, - total_k32, - tid, - ) + self._stage_n64_sfb( + down_sfb_rp, + sfb_base, + expert_idx, + output_tile, + intermediate_slice, + total_output_tiles, + total_k32, + tid, + bounds_smem=smem_base + Int32(self._csf_bounds_offset) + if cutlass.const_expr(self.csf_inline) + else None, + ) else: # Prepared weights remain N256 tile-major. Compact this CTA's @@ -647,10 +627,29 @@ def _run_task( if cutlass.const_expr(self.trellis_direct_lut): trellis_lut_addr = trellis_lut.iterator.toint() - # Keep enough groups in flight to hide global-memory latency while the - # current K128 slice is consumed. Each preload gets its own group, - # including the guarded-empty tail groups, so wait_group below retains - # the current slice's data. + m_blocks = self.tile_m // 16 + n_fragments = self.tile_n // 32 + is_transposed = self.transpose_direct or transpose_grouped + if cutlass.const_expr(is_transposed): + n_fragments = self.tile_n // 64 + + csf_active = ( + valid_rows > Int32(0) + if cutlass.const_expr(self.fused_groups > 1) + else cutlass.Boolean(True) + ) + if cutlass.const_expr(self.csf_inline): + if csf_active: + self.csf_reader.prefetch_column_bounds_smem( + down_sfb_rp.iterator, + expert_idx, + output_tile, + smem_base + Int32(self._csf_bounds_offset), + tid, + num_threads=32, + sync_warp_after=True, + ) + for preload_slice in cutlass.range_constexpr(self.stages - 1): if Int32(preload_slice) < intermediate_tiles: self._stage_slice( @@ -671,11 +670,25 @@ def _run_task( ) cute.arch.cp_async_commit_group() + csf_bases_packed = None + if cutlass.const_expr(self.csf_inline): + csf_r0_init = ( + (warp_idx * Int32(4) + (lane & Int32(1))) * Int32(8) + q + if cutlass.const_expr(is_transposed) + else warp_idx * Int32(32) + q + ) + csf_bases_packed = Uint32(0) + if csf_active: + csf_bases_packed = self.csf_reader.load_lane_bases_packed( + down_sfb_rp.iterator, + expert_idx, + output_tile, + csf_r0_init, + row_stride=16 if is_transposed else 8, + n_fragments=n_fragments, + ) + # Each warp owns tile_m x tile_n/4 and its tile_n/32 N8 fragments. - m_blocks = self.tile_m // 16 - n_fragments = self.tile_n // 32 - if cutlass.const_expr(self.transpose_direct or transpose_grouped): - n_fragments = self.tile_n // 64 facc = tuple( tuple( cute.make_rmem_tensor((4,), cutlass.Float32) @@ -686,6 +699,8 @@ def _run_task( for blk in cutlass.range_constexpr(m_blocks): for nt in cutlass.range_constexpr(n_fragments): facc[blk][nt].fill(0.0) + sfb_reg = cute.make_rmem_tensor((n_fragments,), Uint32) + sfb_reg.fill(Uint32(0)) intermediate_slice = Int32(0) while intermediate_slice < intermediate_tiles: @@ -700,7 +715,7 @@ def _run_task( sfb_base = ( smem_base + Int32(self.sfb_storage_offset) - + stage * Int32(self.sfb_stage_bytes) + + stage * Int32(self._csf_sfb_stage_bytes) ) next_slice = intermediate_slice + Int32(self.stages - 1) @@ -725,14 +740,34 @@ def _run_task( cute.arch.cp_async_wait_group(self.stages - 1) cute.arch.fence_proxy("async.shared", space="cta") cute.arch.sync_threads() - sfb_words = sfb_base if cutlass.const_expr(self.csf_inline): - # Each warp publishes only the 32 rows consumed by its N fragments. assert self.tile_n == 128 and self.num_warps == 4 - sfb_words = smem_base + Int32(self.shared_words * 4) - self.csf_reader.expand_warp_rows( - down_sfb_rp.iterator, sfb_base, sfb_words, warp_idx, lane + csf_r0_loop = ( + (warp_idx * Int32(4) + (lane & Int32(1))) * Int32(8) + q + if cutlass.const_expr(is_transposed) + else warp_idx * Int32(32) + q + ) + self.csf_reader.decode_compact_1bit_words( + down_sfb_rp.iterator, + sfb_base, + smem_base + Int32(self._csf_bounds_offset), + intermediate_slice, + csf_bases_packed, + csf_r0_loop, + sfb_reg, + row_stride=16 if is_transposed else 8, + n_fragments=n_fragments, + aligned_v4_codes=not is_transposed, + hoist_bounds=False, ) + elif cutlass.const_expr(not self.w4a8_trellis): + for nt in cutlass.range_constexpr(n_fragments): + n8 = warp_idx * Int32(n_fragments) + Int32(nt) + if cutlass.const_expr(is_transposed): + n8 = warp_idx * Int32(4) + Int32(nt * 2) + (lane & Int32(1)) + sfb_reg[nt] = ld_shared_u32( + sfb_base + ((n8 * Int32(8) + q) << Int32(2)) + ) asc = cute.make_rmem_tensor((m_blocks,), Uint32) for blk in cutlass.range_constexpr(m_blocks): if cutlass.const_expr(self.direct_routes): @@ -825,22 +860,18 @@ def _run_task( dn_b0[nt] = wb0 dn_b1[nt] = wb1 for nt in cutlass.range_constexpr(n_fragments): - n8 = warp_idx * Int32(n_fragments) + Int32(nt) b0 = dn_b0[nt] b1 = dn_b1[nt] if cutlass.const_expr( self.transpose_direct or transpose_grouped ): - n8 = warp_idx * Int32(4) + Int32(nt * 2) + (lane & Int32(1)) b0 = dn_b0[nt * 2] b1 = dn_b0[nt * 2 + 1] b2 = dn_b1[nt * 2] b3 = dn_b1[nt * 2 + 1] sfb_word = Uint32(0x7F7F7F7F) if cutlass.const_expr(not self.w4a8_trellis): - sfb_word = ld_shared_u32( - sfb_words + ((n8 * Int32(8) + q) << Int32(2)) - ) + sfb_word = sfb_reg[nt] for blk in cutlass.range_constexpr(m_blocks): fragment = facc[blk][nt] if cutlass.const_expr( @@ -1080,9 +1111,7 @@ def _stage_slice_m128( stage_m: cutlass.Constexpr[int], mbar_base=None, l2_policy=None, - sfb_bounds=None, - csf_value_offset=None, - sfb_base_word=None, + bounds_smem=None, ): a_base = smem_base + stage * Int32(self.a_stage_bytes) sfa_base = a_base + Int32(self.a_payload_bytes) @@ -1092,7 +1121,7 @@ def _stage_slice_m128( sfb_base = ( smem_base + Int32(self.sfb_storage_offset) - + stage * Int32(self.sfb_stage_bytes) + + stage * Int32(self._csf_sfb_stage_bytes) ) words_per_row = intermediate_tiles * Int32(32) physical_row_base = Int64(source_m_tile) * Int64(self.source_tile_m) @@ -1190,9 +1219,7 @@ def _stage_slice_m128( total_output_tiles, total_k32, tid, - sfb_bounds, - csf_value_offset, - sfb_base_word, + bounds_smem=bounds_smem, ) else: n32_chunks = self.tile_n // 32 @@ -1268,6 +1295,22 @@ def _run_task_m128( if cutlass.const_expr(self.n64_repacked and self.n64_tail): total_k64 -= Int32(1) + sfb_bounds_smem = ( + smem_base + Int32(self._csf_bounds_offset) + if cutlass.const_expr(self.csf_inline and self.n64_repacked) + else None + ) + if cutlass.const_expr(self.csf_inline and self.n64_repacked): + self.csf_reader.prefetch_column_bounds_smem( + down_sfb_rp.iterator, + expert_idx, + output_tile, + sfb_bounds_smem, + tid, + num_threads=32, + sync_warp_after=not self.use_tma_b, + ) + mbar_base = None l2_policy = None if cutlass.const_expr(self.use_tma_b): @@ -1283,20 +1326,6 @@ def _run_task_m128( cute.arch.mbarrier_init(mbar_base + Int32(s), Int32(1)) cute.arch.sync_threads() - sfb_bounds = None - csf_value_offset = None - sfb_base_word = None - if cutlass.const_expr(self.csf_inline and self.n64_repacked): - csf_value_offset = self.csf_reader.plane.group_value_offset( - down_sfb_rp.iterator - ) - sfb_bounds = self.csf_reader.prefetch_column_bounds( - down_sfb_rp.iterator, expert_idx, output_tile - ) - sfb_base_word = self.csf_reader.prefetch_row_bases( - down_sfb_rp.iterator, expert_idx, output_tile, tid - ) - no_tail_barrier = self.stages >= 3 preload_slices = self.stages - 2 if no_tail_barrier else self.stages - 1 for preload_slice in cutlass.range_constexpr(preload_slices): @@ -1318,12 +1347,22 @@ def _run_task_m128( compute_m, mbar_base=mbar_base, l2_policy=l2_policy, - sfb_bounds=sfb_bounds, - csf_value_offset=csf_value_offset, - sfb_base_word=sfb_base_word, + bounds_smem=sfb_bounds_smem, ) cute.arch.cp_async_commit_group() + sfb_bases_packed = None + csf_r0 = warp_idx * Int32(32) + q + if cutlass.const_expr(self.csf_inline and self.n64_repacked): + sfb_bases_packed = self.csf_reader.load_lane_bases_packed( + down_sfb_rp.iterator, + expert_idx, + output_tile, + csf_r0, + row_stride=8, + n_fragments=4, + ) + m_blocks = compute_m // 16 n_fragments = 4 facc = tuple( @@ -1356,7 +1395,7 @@ def _run_task_m128( sfb_base = ( smem_base + Int32(self.sfb_storage_offset) - + stage * Int32(self.sfb_stage_bytes) + + stage * Int32(self._csf_sfb_stage_bytes) ) next_slice = k64_slice + Int32(preload_slices) @@ -1378,9 +1417,7 @@ def _run_task_m128( compute_m, mbar_base=mbar_base, l2_policy=l2_policy, - sfb_bounds=sfb_bounds, - csf_value_offset=csf_value_offset, - sfb_base_word=sfb_base_word, + bounds_smem=sfb_bounds_smem, ) cute.arch.cp_async_commit_group() cute.arch.cp_async_wait_group(preload_slices) @@ -1391,22 +1428,25 @@ def _run_task_m128( k_half = k64_slice & Int32(1) scale_shift = Uint32(k_half) * Uint32(16) if k_half == Int32(0): - sfb_words = sfb_base if cutlass.const_expr(self.csf_inline): - sfb_words = smem_base + Int32(self.shared_words * 4) - self.csf_reader.expand_warp_rows( + self.csf_reader.decode_compact_1bit_words( down_sfb_rp.iterator, sfb_base, - sfb_words, - warp_idx, - lane, - csf_value_offset, - ) - for nt in cutlass.range_constexpr(n_fragments): - n8 = warp_idx * Int32(4) + Int32(nt) - sfb_reg[nt] = ld_shared_u32( - sfb_words + ((n8 * Int32(8) + q) << Int32(2)) + sfb_bounds_smem, + k64_slice >> Int32(1), + sfb_bases_packed, + csf_r0, + sfb_reg, + row_stride=8, + n_fragments=4, + aligned_v4_codes=True, ) + else: + for nt in cutlass.range_constexpr(n_fragments): + n8 = warp_idx * Int32(4) + Int32(nt) + sfb_reg[nt] = ld_shared_u32( + sfb_base + ((n8 * Int32(8) + q) << Int32(2)) + ) for blk in cutlass.range_constexpr(m_blocks): sf_row = Int32(blk * 16) + q + ((lane & Int32(1)) << Int32(3)) asc[blk] = ld_shared_u32(sfa_base + (sf_row << Int32(2))) diff --git a/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py b/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py index 159eea7b9eb..7b34c972971 100644 --- a/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py +++ b/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py @@ -1320,7 +1320,7 @@ def _validate_fc2_query(query: MoeFC2Query, _device) -> None: validate_query=_validate_query, validate_config=validate_moe_decode_config, default_config=_default_config, - candidate_contract_version=74, + candidate_contract_version=75, knobs=( Knob( name="backend", diff --git a/tests/experimental/b12x/moe/test_mxfp4_csf.py b/tests/experimental/b12x/moe/test_mxfp4_csf.py index 0e91d5a6595..5ada3564d92 100644 --- a/tests/experimental/b12x/moe/test_mxfp4_csf.py +++ b/tests/experimental/b12x/moe/test_mxfp4_csf.py @@ -827,3 +827,183 @@ def test_compiled_csf_packed_routes_restore_poisoned_scratch( csf_inline_scales=False, ), ) + + +@pytest.mark.parametrize( + "h,n,e,topk,tokens,backend,param", + [ + (2048, 320, 8, 5, 1, "micro", 64), + (2048, 320, 8, 5, 1, "micro", 128), + (2048, 320, 8, 5, 4, "micro", 64), + (2048, 320, 8, 5, 32, "dynamic", 16), + (2048, 320, 8, 5, 256, "dynamic", 128), + (2048, 576, 8, 3, 17, "dynamic", 16), + ], +) +def test_w4a8_inline_compact_1bit_exception_overflow_parity( + h, n, e, topk, tokens, backend, param +): + """Bitwise parity for inline compact 1-bit CSF when groups overflow >32 exceptions, + combined with n64_tail (nr=64 / nc=2), odd topk (fused_groups=2 padding), and + poisoned expanded scale scratch.""" + from b12x.moe.fused_moe._csf_preparation import prepare_online_csf_weights + + device = require_b12x() + g = torch.Generator(device=device).manual_seed(17) + + def make_overflow_scales(shape): + base = torch.randint( + 118, 125, shape[:-1] + (1,), generator=g, device=device, dtype=torch.int32 + ) + off = torch.randint(0, 2, shape, generator=g, device=device, dtype=torch.int32) + scales = (base + off).to(torch.uint8) + mask = torch.rand(shape, generator=g, device=device) < 0.14 + wild = torch.randint( + 105, 114, shape, generator=g, device=device, dtype=torch.uint8 + ) + scales = torch.where(mask, wild, scales) + scales[0, :64, :3] = 108 + scales[0, 64 : min(128, shape[1]), :2] = 132 + return scales + + w13 = torch.randint( + 0, 256, (e, 2 * n, h // 2), generator=g, device=device, dtype=torch.uint8 + ) + w2 = torch.randint( + 0, 256, (e, h, n // 2), generator=g, device=device, dtype=torch.uint8 + ) + w13_s = make_overflow_scales((e, 2 * n, h // 32)) + w2_s = make_overflow_scales((e, h, n // 32)) + one = torch.ones(e, device=device, dtype=torch.float32) + + weight_plan = moe.plan_weights( + source=moe.PackedSource(format="fp4_e8m0_k32", w13_layout="w31"), + activation=moe.ActivationSpec( + mode="a8", nonlinearity="silu", io_dtype=torch.bfloat16, swiglu_limit=7.0 + ), + geometry=moe.MoEGeometry(num_experts=e, hidden_size=h, intermediate_size=n), + ) + nat = moe.prepare_weights( + plan=weight_plan, + weights=moe.PackedWeights( + w13=w13.clone(), + w2=w2.clone(), + w13_block_scales=w13_s.clone(), + w2_block_scales=w2_s.clone(), + w13_global_scales=one.clone(), + w2_global_scales=one.clone(), + ), + ) + scratch_scales = ( + torch.empty_like(nat._impl.w1_blockscale).view(torch.uint8), + torch.empty_like(nat._impl.w2_blockscale).view(torch.uint8), + ) + csf = prepare_online_csf_weights( + weight_plan, + moe.PackedWeights( + w13=w13.clone(), + w2=w2.clone(), + w13_block_scales=w13_s.clone(), + w2_block_scales=w2_s.clone(), + w13_global_scales=one.clone(), + w2_global_scales=one.clone(), + ), + scratch_scales, + ) + # Confirm overflow (>32 exceptions in a single group) actually occurred in both planes. + for plane in (csf._impl.nvfp4_csf.first, csf._impl.nvfp4_csf.second): + st = plane.scales.storage.cpu() + geom = plane.scales.geometry + off = ( + st[geom.offsets : geom.offsets + geom.experts * geom.prefixes * 2] + .view(torch.uint16) + .to(torch.int32) + .reshape(geom.experts, geom.prefixes) + ) + max_cnt = max( + int(off[ex, grp + grp // 32 + 1]) - int(off[ex, grp + grp // 32]) + for ex in range(geom.experts) + for grp in range(geom.groups) + ) + assert max_cnt > 32 + + x = torch.randn((tokens, h), generator=g, dtype=torch.bfloat16, device=device) * 0.1 + logits = torch.randn((tokens, e), generator=g, dtype=torch.float32, device=device) + logits[:, 0] += 5.0 + vals, ids = torch.topk(logits, topk, dim=-1) + weights = torch.softmax(vals, dim=-1).to(torch.float32) + ids = ids.to(torch.int32) + + dev_id = detect_device(device).identity + outputs = {} + for kind, owner, inline in (("native", nat, False), ("csf_inl", csf, True)): + plan = moe.plan_execution( + experts=owner, + capacity=moe.ExecutionCapacity(max_tokens=tokens, top_k=topk), + invocation={"fast_math": False}, + routing=moe.RoutingSpec(deterministic_output=True), + ) + base_cfg = plan.contract.default_config(plan.query, dev_id) + if backend == "micro": + cfg = replace( + base_cfg, + backend="micro", + micro_fc1_tile_n=param, + dynamic_tile_m=None, + dynamic_route_mode=None, + csf_inline_scales=inline, + ) + else: + cfg = replace( + base_cfg, + backend="dynamic", + dynamic_tile_m=param, + dynamic_route_mode="grouped", + csf_inline_scales=inline, + ) + plan = replace(plan, override=cfg) + + def prepare_call(state): + sc = tuple( + torch.empty(s.shape, dtype=s.dtype, device=device) + for s in state.scratch.scratch_specs() + ) + out = torch.empty_like(x) + binding = state.bind( + a=x, + topk_ids=ids, + topk_weights=weights, + output=out, + scratch=sc, + input_scales_static=True, + ) + return PreparedCall( + run=lambda: state.run(binding), output=out, owners=(sc, binding) + ) + + with PreparationSession(device=device, autotune=False, compile_workers=8) as sess: + sess.prepare( + (plan.request(name=f"ovf-{kind}-{tokens}-{backend}-{param}", prepare_call=prepare_call),) + ) + sc = tuple( + torch.empty(s.shape, dtype=s.dtype, device=device) + for s in plan.scratch_specs() + ) + out = torch.empty_like(x) + binding = moe.bind( + plan, + a=x, + topk_ids=ids, + topk_weights=weights, + output=out, + scratch=sc, + input_scales_static=True, + ) + if inline: + for buf in scratch_scales: + buf.fill_(0x7F) + moe.run(binding=binding) + torch.cuda.synchronize() + outputs[kind] = out.clone() + + assert torch.equal(outputs["csf_inl"], outputs["native"])