From d8b6a60e24ed349c05f04e12484df0fbd3e0d56d Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:53:54 -0600 Subject: [PATCH 1/2] perf(b12x/moe): vectorize the W4A8 M128 down-projection epilogue Why: SM120 W4A8 M128 materialized MoE uses scalar shared loads and BF16 stores or atomic reductions in the down-projection epilogue. Tasks with 65 to 96 valid rows pad to 128 rows, and the epilogue retains a tail barrier when the pipeline has three or more stages. What: - Load and write 128-bit vectors in W4A8MaterializedPhase2Kernel, using st_global_v4_u32 for deterministic output and red_add_global_v4_bf16x2 for routed accumulation when tile_n % 8 == 0, scatter_output base is 16-byte aligned, and scatter_n % 8 == 0, falling back to 4-byte st_global_u32 / red_add_global_bf16x2 otherwise. - Guard Phase 0 st_global_v4_u32 zeroing and the monolithic MoEDynamicKernelBackend scatter_add_v4_bf16x2 epilogue on 16-byte base alignment (and scatter_N % 8 == 0 / tile_shape_mnk[1] % 8 == 0 with a 4x scatter_add_bf16x2 fallback at +0/+4/+8/+12 bytes), lower scatter_output assumed_align to 4 in _get_dynamic_kernel and _launch_dynamic_flat so LLVM preserves the runtime checks, and enforce output alignment in b12x_moe_fp4 (4-byte for dynamic non-raw-route paths, 16-byte fail-closed for micro and raw-route paths). - Lower output assumed_align to 4 in W4A16TopKSumKernel (sum_launch.py), use 16-byte-aligned fc2_out for unused dummy pointer arguments, guard vec8_fast_path st_global_v4_u32 on 16-byte output alignment with a 4x st_global_u32 fallback in sum.py, and bump the moe.w4a16.topk_sum compile spec from 7 to 8. - Add the compute_m=96 bucket in both materialized kernels (asserting compute_m % 8 == 0 in Phase 2 epilogue), skip the tail barrier when stages >= 3 (preload_slices = stages - 2 keeps next_stage disjoint from the prior compute stage), and bump the integration.tp_moe.dynamic compile spec from 22 to 23. - Add CPU invariant, direct Phase 2 alignment/bucket, monolithic NVFP4 dynamic 4B/8B/12B alignment fallback, dynamic 4B/2B and micro 16B alignment, and direct W4A16TopKSumKernel 4B-aligned output tests in test_w4a8_prefill_m128.py and test_w4a16_route_sum.py. Result: Single-GPU NVIDIA GeForce RTX 5090 (SM120, driver 610.88, PyTorch 2.14.1+cu132, CUTLASS DSL 4.8.1) CUDA-graph A/B versus base 0ddf1a46a8 on W4A8 M128 prefill (E=384, H=5120, N=576, top-k 6, Zipf 1.1, prequantized MXFP8 input, internal route planner, inline CSF scales, 3 interleaved trials x 30 replays with 128 MiB L2 flush; multi-GPU / TP4 not exercised): - M=4096, det=False: 1808.35 us (trials 1807.33/1808.35/1809.41) -> 1774.40 us (trials 1703.71/1774.40/1776.40), -33.95 us (-1.88%) - M=8192, det=False: 2596.64 us (trials 2591.71/2596.64/2632.18) -> 2551.54 us (trials 2549.55/2551.54/2553.73), -45.10 us (-1.74%) - M=8192, det=True: 2993.09 us (trials 2990.13/2993.09/3004.70) -> 2975.62 us (trials 2975.52/2975.62/2983.70), -17.47 us (-0.58%) Per-kernel CUDA profiler median on M=8192, det=False (15 L2-flushed runs): W4A8MaterializedPhase2Kernel 972.24 -> 931.87 us (-4.15%), W4A8MaterializedPhase1Kernel 1750.98 -> 1704.90 us (-2.63%). Evidence: Verified locally on single-GPU RTX 5090 (SM120, PyTorch 2.14.1+cu132, CUTLASS DSL 4.8.1) from exact git archive HEAD (multi-GPU / TP4 not exercised here): - tests/experimental/b12x/moe/test_w4a8_prefill_m128.py: 37 passed, 0 failed (including test_w4a8_m128_validation_and_heuristics, test_w4a8_m128_compute_m96_and_no_tail_barrier_invariants, test_w4a8_m128_phase2_alignment_fallback_and_compute_m96_direct [False/True], test_w4a8_m128_output_2byte_alignment_rejected [dynamic 4B + micro 16B fail-closed], test_dynamic_monolithic_nvfp4_output_4byte_alignment_fallback [128-128, 512-16] across 4B/8B/12B mod-16 output offsets, and test_w4a8_m128_output_alignment_fallback_and_rejection [False/True] across 4B/8B/12B mod-16 output offsets) - tests/experimental/b12x/moe/test_w4a16_route_sum.py: 10 passed, 0 failed (including test_route_sum_4byte_aligned_output [False/True]) - tests/experimental/b12x/moe/test_route_sum_compile.py: 14 passed, 0 failed - ruff 0.12.8 check clean across all 9 touched files; git merge-tree --write-tree 335459b2 HEAD clean; git diff --check clean. Discord: Dooner Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> --- .../b12x/_lib/intrinsics/atomics.py | 34 + .../moe/_shared/kernels/dynamic/kernel.py | 61 +- .../moe/_shared/kernels/w4a16/kernel/sum.py | 26 +- .../kernels/w4a16/kernel/sum_launch.py | 8 +- .../b12x/moe/_shared/kernels/w4a8_phase1.py | 2 + .../b12x/moe/_shared/kernels/w4a8_phase2.py | 71 +- .../experimental/b12x/moe/fused_moe/_impl.py | 13 +- .../b12x/moe/test_w4a16_route_sum.py | 64 ++ .../b12x/moe/test_w4a8_prefill_m128.py | 608 +++++++++++++++++- 9 files changed, 834 insertions(+), 53 deletions(-) diff --git a/flashinfer/experimental/b12x/_lib/intrinsics/atomics.py b/flashinfer/experimental/b12x/_lib/intrinsics/atomics.py index 51d4c3f31dc..e3a4e607201 100644 --- a/flashinfer/experimental/b12x/_lib/intrinsics/atomics.py +++ b/flashinfer/experimental/b12x/_lib/intrinsics/atomics.py @@ -210,6 +210,40 @@ def red_add_global_bf16x2(addr: Int64, packed: Uint32, *, loc=None, ip=None): ) +@dsl_user_op +def red_add_global_v4_bf16x2( + addr: Int64, + v0: Uint32, + v1: Uint32, + v2: Uint32, + v3: Uint32, + *, + loc=None, + ip=None, +): + """No-return global 128-bit atomic add of four packed bf16x2 values (8 contiguous bf16). + + Requires SM90+/SM120+ and a 16-byte-aligned global address. + """ + llvm.inline_asm( + None, + [ + Int64(addr).ir_value(loc=loc, ip=ip), + Uint32(v0).ir_value(loc=loc, ip=ip), + Uint32(v1).ir_value(loc=loc, ip=ip), + Uint32(v2).ir_value(loc=loc, ip=ip), + Uint32(v3).ir_value(loc=loc, ip=ip), + ], + "red.relaxed.gpu.global.add.noftz.v4.bf16x2 [$0], {$1, $2, $3, $4};", + "l,r,r,r,r", + has_side_effects=True, + is_align_stack=False, + asm_dialect=llvm.AsmDialect.AD_ATT, + loc=loc, + ip=ip, + ) + + @dsl_user_op def red_max_global_f32_nonnegative(addr: Int64, val: Float32, *, loc=None, ip=None): """No-return global max reduction for a non-negative fp32 value. diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py b/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py index 64a801d2a25..141daccb5bd 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py @@ -2916,7 +2916,9 @@ class Storage: ): scatter_rows = Int32(scatter_output.shape[0]) scatter_total_u32 = scatter_rows * cols_u32 - scatter_vecs = scatter_total_u32 // Int32(4) + scatter_vecs = Int32(0) + if (scatter_base & Int64(15)) == Int64(0): + scatter_vecs = scatter_total_u32 // Int32(4) zero_u32 = Uint32(0) zv = flat_tid while zv < scatter_vecs: @@ -7308,6 +7310,11 @@ class Storage: # handles B_down availability for FC2 GEMM. # ============================================================ scatter_N = Int32(scatter_output.shape[1]) + scatter_vec16_aligned = ( + cutlass.const_expr(self.tile_shape_mnk[1] % 8 == 0) + and ((scatter_base & Int64(15)) == Int64(0)) + and ((scatter_N & Int32(7)) == Int32(0)) + ) lane_id = Int32(tidx) & Int32(31) warp_in_tile = Int32(tidx) >> Int32(5) warp_m_base = (warp_in_tile >> Int32(1)) * Int32(64) @@ -8199,20 +8206,44 @@ class Storage: + sc_v7 ) else: - scatter_add_v4_bf16x2( - get_ptr_as_int64( - scatter_output, - tok * scatter_N + global_col, - ), - sc_v0, - sc_v1, - sc_v2, - sc_v3, - sc_v4, - sc_v5, - sc_v6, - sc_v7, - ) + scatter_addr = get_ptr_as_int64( + scatter_output, + Int64(tok) * Int64(scatter_N) + + Int64(global_col), + ) + if scatter_vec16_aligned: + scatter_add_v4_bf16x2( + scatter_addr, + sc_v0, + sc_v1, + sc_v2, + sc_v3, + sc_v4, + sc_v5, + sc_v6, + sc_v7, + ) + else: + scatter_add_bf16x2( + scatter_addr, + sc_v0, + sc_v1, + ) + scatter_add_bf16x2( + scatter_addr + Int64(4), + sc_v2, + sc_v3, + ) + scatter_add_bf16x2( + scatter_addr + Int64(8), + sc_v4, + sc_v5, + ) + scatter_add_bf16x2( + scatter_addr + Int64(12), + sc_v6, + sc_v7, + ) vec_idx += Int32(self.num_threads_per_warp) # All warps must finish the current scatter diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum.py index 61b0e488389..e7aa267fa64 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum.py @@ -11,7 +11,11 @@ _covering_count, _materialize_w4a16_topk_route_f32, ) -from b12x._lib.intrinsics.memory import ld_global_v4_u32, st_global_v4_u32 +from b12x._lib.intrinsics.memory import ( + ld_global_v4_u32, + st_global_u32, + st_global_v4_u32, +) from b12x.comm.pcie._cute_intrinsics import ( pack_f32x2_to_bf16x2, pack_f32x2_to_f16x2, @@ -569,6 +573,7 @@ class RouteShm: ) fc2_base_addr = Int64(fc2_flat.iterator.toint()) out_base_addr = Int64(output_flat.iterator.toint()) + out_aligned16 = (out_base_addr & Int64(15)) == Int64(0) pack = tile_start + tid while pack < tile_end: acc = cute.make_rmem_tensor((8,), cutlass.Float32) @@ -591,13 +596,18 @@ class RouteShm: acc[p * 2] = acc[p * 2] + _materialize_w4a16_topk_route_f32(lo) acc[p * 2 + 1] = acc[p * 2 + 1] + _materialize_w4a16_topk_route_f32(hi) i += Int32(1) - st_global_v4_u32( - out_base_addr + (Int64(tok) * Int64(packs) + Int64(pack)) * Int64(16), - self._pack_pair(acc[0], acc[1]), - self._pack_pair(acc[2], acc[3]), - self._pack_pair(acc[4], acc[5]), - self._pack_pair(acc[6], acc[7]), - ) + w0 = self._pack_pair(acc[0], acc[1]) + w1 = self._pack_pair(acc[2], acc[3]) + w2 = self._pack_pair(acc[4], acc[5]) + w3 = self._pack_pair(acc[6], acc[7]) + out_addr = out_base_addr + (Int64(tok) * Int64(packs) + Int64(pack)) * Int64(16) + if out_aligned16: + st_global_v4_u32(out_addr, w0, w1, w2, w3) + else: + st_global_u32(out_addr, w0) + st_global_u32(out_addr + Int64(4), w1) + st_global_u32(out_addr + Int64(8), w2) + st_global_u32(out_addr + Int64(12), w3) pack += Int32(self.vec8_threads) return idx = Int32(bidx) * Int32(self.cta_threads) + Int32(tidx) diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum_launch.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum_launch.py index 1352e4d89bd..acb093d576d 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum_launch.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a16/kernel/sum_launch.py @@ -81,7 +81,7 @@ def compile_w4a16_topk_sum( fc2_fake = make_ptr(cutlass_dtype, 16, cute.AddressSpace.gmem, assumed_align=16) output_dtype = cutlass.Float32 if full_rotation or float32_output else cutlass_dtype - output_fake = make_ptr(output_dtype, 16, cute.AddressSpace.gmem, assumed_align=16) + output_fake = make_ptr(output_dtype, 4, cute.AddressSpace.gmem, assumed_align=4) topk_weights_fake = make_ptr( cutlass.Float32, 4, cute.AddressSpace.gmem, assumed_align=4 ) @@ -126,7 +126,7 @@ def compile_w4a16_topk_sum( current_cuda_stream(), compile_spec=KernelCompileSpec.from_key( "moe.w4a16.topk_sum", - 7, + 8, cache_key, ), ) @@ -206,7 +206,7 @@ def _w4a16_topk_sum_launch_flat( broadcast_svh=broadcast_svh, float32_output=output.dtype == torch.float32, ) - dummy_addr = output.data_ptr() + dummy_addr = fc2_out.data_ptr() weights_addr = dummy_addr if topk_weights is None else topk_weights.data_ptr() route_ids_addr = ( dummy_addr if route_expert_ids is None else route_expert_ids.data_ptr() @@ -230,7 +230,7 @@ def _w4a16_topk_sum_launch_flat( else _cutlass_element_dtype(element_dtype), output.data_ptr(), cute.AddressSpace.gmem, - assumed_align=16, + assumed_align=4, ), make_ptr( cutlass.Float32, diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py index c8a6ec7faab..6fce5957ec9 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py @@ -2101,6 +2101,8 @@ class Storage: self._run_task(*task_args, 32) elif valid_rows <= Int32(64): self._run_task(*task_args, 64) + elif valid_rows <= Int32(96): + self._run_task(*task_args, 96) else: self._run_task(*task_args, 128) elif cutlass.const_expr(self.fast_m128_src and self.tile_m == 64): diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py index 7fa6a02dfdf..e1f36328d82 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py @@ -29,11 +29,13 @@ ld_shared_v4_u32, shared_ptr_to_u32, st_global_u32, + st_global_v4_u32, ) from b12x._lib.intrinsics.mma import e2m1x8_to_qmma_e2m1x8, mxfp8_mma_m16n8k32_f32_e2m1 from b12x._lib.intrinsics.atomics import ( ld_shared_u32, red_add_global_bf16x2, + red_add_global_v4_bf16x2, scatter_add_bf16x2, ) from b12x._lib.intrinsics.packed import pack_f32x2_to_bfloat2 @@ -1286,7 +1288,7 @@ def _run_task_m128( down_sfb_rp.iterator, expert_idx, output_tile, tid ) - no_tail_barrier = False + 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): if Int32(preload_slice) < total_k64: @@ -1532,27 +1534,52 @@ def _run_task_m128( cute.arch.sync_threads() out_col_base = output_tile * Int32(self.tile_n) + assert compute_m % 8 == 0 rows_per_warp = compute_m // 4 - for r in cutlass.range_constexpr(rows_per_warp): - row = warp_idx * Int32(rows_per_warp) + Int32(r) - if row < valid_rows: - tok = ld_shared_u32(epi_tok_base + (row << Int32(2))).to(Int32) - row_smem = smem_base + row * epi_row_bytes - v0 = ld_shared_u32(row_smem + (lane << Int32(2))) - v1 = ld_shared_u32(row_smem + Int32(128) + (lane << Int32(2))) - row_ptr_base = Int64(tok) * Int64(scatter_n) + Int64(out_col_base) - addr0 = get_ptr_as_int64( - scatter_output, row_ptr_base + Int64(lane << Int32(1)) - ) - addr1 = get_ptr_as_int64( - scatter_output, row_ptr_base + Int64(Int32(64) + (lane << Int32(1))) - ) - if cutlass.const_expr(self.deterministic_output): - st_global_u32(addr0, v0) - st_global_u32(addr1, v1) - else: - red_add_global_bf16x2(addr0, v0) - red_add_global_bf16x2(addr1, v1) + sub_lane = lane & Int32(15) + lane_row_off = lane >> Int32(4) + scatter_base_ptr = get_ptr_as_int64(scatter_output, Int64(0)) + vec16_aligned = ( + cutlass.const_expr(self.tile_n % 8 == 0) + and ((scatter_base_ptr & Int64(15)) == Int64(0)) + and ((scatter_n & Int32(7)) == Int32(0)) + ) + if vec16_aligned: + for rp in cutlass.range_constexpr(rows_per_warp // 2): + row = warp_idx * Int32(rows_per_warp) + Int32(rp * 2) + lane_row_off + if row < valid_rows: + tok = ld_shared_u32(epi_tok_base + (row << Int32(2))).to(Int32) + row_smem = smem_base + row * epi_row_bytes + v0, v1, v2, v3 = ld_shared_v4_u32(row_smem + (sub_lane << Int32(4))) + row_ptr_base = Int64(tok) * Int64(scatter_n) + Int64(out_col_base) + addr = get_ptr_as_int64( + scatter_output, row_ptr_base + Int64(sub_lane << Int32(3)) + ) + if cutlass.const_expr(self.deterministic_output): + st_global_v4_u32(addr, v0, v1, v2, v3) + else: + red_add_global_v4_bf16x2(addr, v0, v1, v2, v3) + else: + for rp in cutlass.range_constexpr(rows_per_warp // 2): + row = warp_idx * Int32(rows_per_warp) + Int32(rp * 2) + lane_row_off + if row < valid_rows: + tok = ld_shared_u32(epi_tok_base + (row << Int32(2))).to(Int32) + row_smem = smem_base + row * epi_row_bytes + v0, v1, v2, v3 = ld_shared_v4_u32(row_smem + (sub_lane << Int32(4))) + row_ptr_base = Int64(tok) * Int64(scatter_n) + Int64(out_col_base) + addr = get_ptr_as_int64( + scatter_output, row_ptr_base + Int64(sub_lane << Int32(3)) + ) + if cutlass.const_expr(self.deterministic_output): + st_global_u32(addr, v0) + st_global_u32(addr + Int64(4), v1) + st_global_u32(addr + Int64(8), v2) + st_global_u32(addr + Int64(12), v3) + else: + red_add_global_bf16x2(addr, v0) + red_add_global_bf16x2(addr + Int64(4), v1) + red_add_global_bf16x2(addr + Int64(8), v2) + red_add_global_bf16x2(addr + Int64(12), v3) cute.arch.sync_threads() @cute.jit @@ -1861,6 +1888,8 @@ class Storage: self._run_task_m128(*task_args, 32) elif valid_rows <= Int32(64): self._run_task_m128(*task_args, 64) + elif valid_rows <= Int32(96): + self._run_task_m128(*task_args, 96) else: self._run_task_m128(*task_args, 128) else: diff --git a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py index 42bec4d070d..470af81b610 100644 --- a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py +++ b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py @@ -12391,9 +12391,9 @@ def _get_dynamic_kernel( ) scatter_fake = make_ptr( cutlass.Float32 if raw_routes else a_dtype, - 16, + 4, cute.AddressSpace.gmem, - assumed_align=16, + assumed_align=4, ) token_map_fake = make_ptr(cutlass.Int32, 4, cute.AddressSpace.gmem, assumed_align=4) token_weights_fake = make_ptr( @@ -12486,7 +12486,7 @@ def _get_dynamic_kernel( ), compile_spec=KernelCompileSpec.from_key( "integration.tp_moe.dynamic", - 22, + 23, cache_key, ), dsl_compile_options=dsl_compile_options, @@ -12983,7 +12983,7 @@ def _gptr(dtype, t, align=16): w1_alpha, w2_alpha, down_input_scale, - _gptr(cutlass.Float32 if raw_routes else cutlass.BFloat16, scatter_output), + _gptr(cutlass.Float32 if raw_routes else cutlass.BFloat16, scatter_output, 4), _gptr(cutlass.Int32, token_map, 4), _gptr(cutlass.Float32, token_weights, 4), m, @@ -14930,6 +14930,11 @@ def b12x_moe_fp4(*, binding: TPMoEFP4Binding) -> torch.Tensor: ) if not scatter_output.is_contiguous(): raise ValueError("output must be contiguous") + required_output_align = 4 if (impl == "dynamic" and not raw_routes) else 16 + if int(scatter_output.data_ptr()) % required_output_align != 0: + raise ValueError( + f"output must be at least {required_output_align}-byte aligned" + ) compact_w4a8_micro = bool( impl == "micro" diff --git a/tests/experimental/b12x/moe/test_w4a16_route_sum.py b/tests/experimental/b12x/moe/test_w4a16_route_sum.py index ac2851d27a4..f7e778cda2d 100644 --- a/tests/experimental/b12x/moe/test_w4a16_route_sum.py +++ b/tests/experimental/b12x/moe/test_w4a16_route_sum.py @@ -75,3 +75,67 @@ def run(): torch.cuda.synchronize() assert torch.cuda.memory_stats()["allocation.all.allocated"] == allocated torch.testing.assert_close(output, expected, rtol=0, atol=0) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") +@pytest.mark.parametrize("weighted", [False, True]) +def test_route_sum_4byte_aligned_output(weighted): + """vec8_fast_path falls back to 4B stores for non-16B 4B-aligned output views.""" + torch.manual_seed(912 + int(weighted)) + rows, topk, hidden, experts = 32, 6, 512, 8 + ids = torch.randint(experts, (rows, topk), device="cuda", dtype=torch.int32) + ids[-4:] = -1 + values = torch.randn((rows, topk, hidden), device="cuda", dtype=torch.bfloat16) + weights = torch.randint(1, 5, (rows, topk), device="cuda").float() / 4 + launcher = compile_w4a16_topk_sum( + m=rows, + topk=topk, + hidden_size=hidden, + route_ids_dtype=torch.int32, + num_experts=experts, + route_num_experts=experts, + use_expert_map=False, + apply_topk_weights=weighted, + ) + + ref_out = torch.full( + (rows, hidden), float("nan"), device="cuda", dtype=torch.bfloat16 + ) + _w4a16_topk_sum_launch_flat( + values, + ref_out, + rows, + topk, + hidden, + "bf16", + torch.cuda.current_stream().cuda_stream, + num_experts=experts, + route_expert_ids=ids, + topk_weights=weights if weighted else None, + launcher=launcher, + ) + torch.cuda.synchronize() + + backing = torch.full( + (rows * hidden + 16,), float("nan"), device="cuda", dtype=torch.bfloat16 + ) + for elem_offset in (2, 4, 6): + out4 = backing[elem_offset : elem_offset + rows * hidden].view(rows, hidden) + assert out4.is_contiguous() + assert out4.data_ptr() % 16 == elem_offset * 2 + out4.fill_(float("nan")) + _w4a16_topk_sum_launch_flat( + values, + out4, + rows, + topk, + hidden, + "bf16", + torch.cuda.current_stream().cuda_stream, + num_experts=experts, + route_expert_ids=ids, + topk_weights=weights if weighted else None, + launcher=launcher, + ) + torch.cuda.synchronize() + torch.testing.assert_close(out4, ref_out, rtol=0, atol=0) diff --git a/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py b/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py index 48e84715526..08c9c4fd341 100644 --- a/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py +++ b/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py @@ -286,13 +286,18 @@ def _run_moe( route_planner: str, csf_inline: bool = False, deterministic: bool = True, + output: torch.Tensor | None = None, ) -> torch.Tensor: prequant = a_vals is not None M = a_vals.shape[0] if prequant else x_bf16.shape[0] K = a_vals.shape[1] if prequant else x_bf16.shape[1] top_k = topk_ids.shape[1] device = topk_ids.device - out = torch.full((M, K), -99.0, dtype=torch.bfloat16, device=device) + out = ( + output + if output is not None + else torch.full((M, K), -99.0, dtype=torch.bfloat16, device=device) + ) plan = fused_moe.plan_execution( experts=experts, @@ -820,3 +825,604 @@ def _prep(state): graph.reset() gc.collect() torch.cuda.empty_cache() + + +@pytest.mark.parametrize("live_rows", [65, 96, 97]) +def test_w4a8_m128_atomic_epilogue_preserves_each_sector(live_rows): + device = require_b12x() + m, k, n = 128, 512, 576 + experts, *_ = _build_experts(4, k, n, device, seed=430) + gen = torch.Generator(device=device).manual_seed(431) + x = torch.randn((m, k), generator=gen, dtype=torch.bfloat16, device=device) + a, scales = _quantize_mxfp8(x * 0.25) + # A single route per live row makes the atomic result order-independent. + routes = torch.full((m, 1), -1, dtype=torch.int64, device=device) + routes[:live_rows] = 0 + weights = routes.ge(0).to(torch.float32) + kwargs = dict( + a_vals=a, + a_scales=scales, + topk_ids=routes, + topk_weights=weights, + route_planner="internal", + deterministic=False, + ) + # M64 retains the barrier at two stages. M128 has three stages and + # switches dispatch buckets at 64 and 96 rows. + ref = _run_moe(experts, tile_m=64, **kwargs) + got = _run_moe(experts, tile_m=128, **kwargs) + assert torch.isfinite(ref).all() + sectors = ref[:live_rows].reshape(live_rows, -1, 8) + assert sectors.ne(0).any(dim=-1).all() + assert sectors[:, 1:].ne(sectors[:, :-1]).any(dim=-1).all() + torch.testing.assert_close(got, ref, rtol=0, atol=0) + + dropped = got.clone() + dropped[live_rows - 1, -8:] = 0 + with pytest.raises(AssertionError): + torch.testing.assert_close(dropped, ref, rtol=0, atol=0) + swapped = got.clone() + swapped[live_rows - 1, -8:] = got[live_rows - 1, -16:-8] + with pytest.raises(AssertionError): + torch.testing.assert_close(swapped, ref, rtol=0, atol=0) + + +def test_w4a8_m128_compute_m96_and_no_tail_barrier_invariants(): + """CPU-only verification of compute_m=96 bounds, SMEM sizing, and 3-stage pipeline safety.""" + from b12x.moe._shared.kernels.w4a8_phase1 import W4A8MaterializedPhase1Kernel + from b12x.moe._shared.kernels.w4a8_phase2 import W4A8MaterializedPhase2Kernel + + for n64_repacked in (False, True): + p1 = W4A8MaterializedPhase1Kernel( + source_tile_m=128, n64_repacked=n64_repacked, num_topk=1 + ) + p2 = W4A8MaterializedPhase2Kernel(source_tile_m=128, n64_repacked=n64_repacked) + assert p1.tile_m == 128 and p1.tile_n == 64 and p1.stages == 3 + assert p2.tile_m == 128 and p2.tile_n == 128 and p2.stages == 3 + assert p2.tile_n % 8 == 0 + + for compute_m in (32, 64, 96, 128): + assert compute_m % 16 == 0 + assert compute_m % 8 == 0 + # Phase 1 M128xN64 epilogue covers all compute_m rows cleanly. + rows_per_iter = p1.threads_per_cta // 4 + assert compute_m % rows_per_iter == 0 + covered_p1 = { + (tid >> 2) + r * rows_per_iter + for r in range(compute_m // rows_per_iter) + for tid in range(p1.threads_per_cta) + } + assert covered_p1 == set(range(compute_m)) + # Phase 2 M128xN128 epilogue covers all compute_m rows and fits in SMEM. + rows_per_warp = compute_m // 4 + assert rows_per_warp % 2 == 0 + covered_p2 = { + w * rows_per_warp + rp * 2 + (lane >> 4) + for w in range(p2.num_warps) + for rp in range(rows_per_warp // 2) + for lane in range(32) + } + assert covered_p2 == set(range(compute_m)) + assert compute_m * (272 + 4 + 4) <= p2.shared_bytes + + # Verify no_tail_barrier = (stages >= 3) with preload_slices = stages - 2 has + # zero WAR hazards: in every iteration t, the stage being written (next_stage) + # is disjoint from both the previous iteration's compute stage (still read by + # slower warps before sync_threads) and all in-flight preloaded stages. + for stages in (3, 4, 5): + preload_slices = stages - 2 + for total_k64 in range(1, 16): + stage = 0 + next_stage = preload_slices + in_flight = set(range(min(preload_slices, total_k64))) + prev_compute_stage = None + for k64_slice in range(total_k64): + next_slice = k64_slice + preload_slices + if next_slice < total_k64: + assert next_stage != prev_compute_stage + assert next_stage not in in_flight + in_flight.add(next_stage) + assert stage in in_flight + in_flight.remove(stage) + prev_compute_stage = stage + stage = (stage + 1) % stages + next_stage = (next_stage + 1) % stages + assert not in_flight + + +@pytest.mark.parametrize("deterministic", [False, True]) +def test_w4a8_m128_phase2_alignment_fallback_and_compute_m96_direct( + deterministic: bool, +): + """Direct SM120 Phase-2 check across compute_m buckets and 16B/4B/odd-stride alignment.""" + import cutlass + import cutlass.cute as cute + from cutlass.cute.runtime import make_ptr + + from b12x._lib.utils.device import current_cuda_stream + from b12x.moe._shared.kernels.w4a8_phase2 import W4A8MaterializedPhase2Kernel + + device = require_b12x() + E, M, N, K = 2, 128, 512, 512 + inter_tiles = N // 128 + packed_out_tiles = K // 256 + words_per_row = inter_tiles * 32 + gen = torch.Generator(device="cpu").manual_seed(437 + int(deterministic)) + inter_vals = torch.randint( + 0x30, 0x48, (M * words_per_row * 4,), generator=gen, dtype=torch.uint8 + ).view(torch.uint32) + inter_scales = torch.full((inter_tiles * M,), 0x7F7F7F7F, dtype=torch.int32).view( + torch.uint32 + ) + inter = torch.cat([inter_vals, inter_scales]).to(device=device) + down_rp_words = E * K * (N // 32) * 4 + down_rp = torch.randint( + 0, 1 << 30, (down_rp_words,), generator=gen, dtype=torch.int32 + ).to(device=device, dtype=torch.uint32) + down_sfb = torch.full( + (E * (K // 128) * inter_tiles * 128,), + 0x7F7F7F7F, + dtype=torch.int32, + device=device, + ).to(torch.uint32) + tok_map = torch.arange(M, dtype=torch.int32, device=device) + tok_w = torch.full((M,), 0.5, dtype=torch.float32, device=device) + task_expert = torch.zeros((inter_tiles,), dtype=torch.int32, device=device) + task_valid = torch.full((inter_tiles,), 96, dtype=torch.int32, device=device) + expert_base = torch.tensor([0, 1, 1], dtype=torch.int32, device=device) + alpha = torch.ones((E,), dtype=torch.float32, device=device) + gs = torch.ones((E,), dtype=torch.float32, device=device) + lut = torch.zeros((1,), dtype=torch.uint8, device=device) + + p2 = W4A8MaterializedPhase2Kernel( + source_tile_m=128, + n64_repacked=True, + deterministic_output=deterministic, + ) + + def _p(dtype, t, align=16): + return make_ptr( + dtype, t.data_ptr(), cute.AddressSpace.gmem, assumed_align=align + ) + + @cute.jit + def _wrap( + inter_p, + drp_p, + dsfb_p, + sc_p, + tm_p, + tw_p, + te_p, + tv_p, + eb_p, + al_p, + gs_p, + lut_p, + sc_n, + stream, + ): + inter_t = cute.make_tensor( + inter_p, cute.make_layout((inter.numel(),), stride=(1,)) + ) + drp_t = cute.make_tensor( + drp_p, cute.make_layout((down_rp.numel(),), stride=(1,)) + ) + dsfb_t = cute.make_tensor( + dsfb_p, cute.make_layout((down_sfb.numel(),), stride=(1,)) + ) + sc_t = cute.make_tensor(sc_p, cute.make_layout((M, sc_n), stride=(sc_n, 1))) + tm_t = cute.make_tensor(tm_p, cute.make_layout((M,), stride=(1,))) + tw_t = cute.make_tensor(tw_p, cute.make_layout((M,), stride=(1,))) + te_t = cute.make_tensor(te_p, cute.make_layout((inter_tiles,), stride=(1,))) + tv_t = cute.make_tensor(tv_p, cute.make_layout((inter_tiles,), stride=(1,))) + eb_t = cute.make_tensor(eb_p, cute.make_layout((E + 1,), stride=(1,))) + al_t = cute.make_tensor(al_p, cute.make_layout((E,), stride=(1,))) + gs_t = cute.make_tensor(gs_p, cute.make_layout((E,), stride=(1,))) + lut_t = cute.make_tensor(lut_p, cute.make_layout((1,), stride=(1,))) + p2( + inter_t, + drp_t, + dsfb_t, + sc_t, + tm_t, + tw_t, + te_t, + tv_t, + eb_t, + al_t, + gs_t, + lut_t, + cutlass.Int32(inter_tiles), + cutlass.Int32(packed_out_tiles), + cutlass.Int32(4), + cutlass.Int32(0), + stream, + ) + + out_16 = torch.zeros((M, K), dtype=torch.bfloat16, device=device) + compiled = cute.compile( + _wrap, + _p(cutlass.Uint32, inter), + _p(cutlass.Uint32, down_rp), + _p(cutlass.Uint32, down_sfb), + _p(cutlass.BFloat16, out_16, 4), + _p(cutlass.Int32, tok_map, 4), + _p(cutlass.Float32, tok_w, 4), + _p(cutlass.Int32, task_expert, 4), + _p(cutlass.Int32, task_valid, 4), + _p(cutlass.Int32, expert_base, 4), + _p(cutlass.Float32, alpha, 4), + _p(cutlass.Float32, gs, 4), + _p(cutlass.Uint8, lut, 4), + cutlass.Int32(K), + current_cuda_stream(), + ) + + backing4 = torch.zeros((M * K + 8,), dtype=torch.bfloat16, device=device) + out_4 = backing4[2 : 2 + M * K].view(M, K) + assert out_4.is_contiguous() and out_4.data_ptr() % 16 == 4 + out_odd = torch.zeros((M, K + 4), dtype=torch.bfloat16, device=device) + assert out_odd.data_ptr() % 16 == 0 and out_odd.shape[1] % 8 == 4 + + def _run(buf: torch.Tensor, stride_n: int): + buf.zero_() + compiled( + _p(cutlass.Uint32, inter), + _p(cutlass.Uint32, down_rp), + _p(cutlass.Uint32, down_sfb), + _p(cutlass.BFloat16, buf, 4), + _p(cutlass.Int32, tok_map, 4), + _p(cutlass.Float32, tok_w, 4), + _p(cutlass.Int32, task_expert, 4), + _p(cutlass.Int32, task_valid, 4), + _p(cutlass.Int32, expert_base, 4), + _p(cutlass.Float32, alpha, 4), + _p(cutlass.Float32, gs, 4), + _p(cutlass.Uint8, lut, 4), + cutlass.Int32(stride_n), + current_cuda_stream(), + ) + torch.cuda.synchronize() + + for live_rows in (32, 64, 65, 96, 97, 128): + task_valid.fill_(live_rows) + _run(out_16, K) + _run(out_4, K) + _run(out_odd, K + 4) + assert torch.isfinite(out_16).all() + assert out_16[:live_rows].ne(0).any() + if live_rows < M: + assert out_16[live_rows:].eq(0).all() + assert out_odd[:, K:].eq(0).all() + assert torch.equal(out_16.view(torch.uint16), out_4.view(torch.uint16)) + assert torch.equal( + out_16.view(torch.uint16), out_odd[:, :K].contiguous().view(torch.uint16) + ) + + +def test_w4a8_m128_output_2byte_alignment_rejected(): + """2-byte dynamic output and 4-byte micro output fail closed before launch.""" + device = require_b12x() + m, k, n = 128, 512, 576 + experts, *_ = _build_experts(4, k, n, device, seed=438) + gen = torch.Generator(device=device).manual_seed(439) + x = torch.randn((m, k), generator=gen, dtype=torch.bfloat16, device=device) + a, scales = _quantize_mxfp8(x * 0.25) + routes = torch.full((m, 1), -1, dtype=torch.int64, device=device) + routes[:96] = 0 + weights = routes.ge(0).to(torch.float32) + + backing2 = torch.empty((m * k + 8,), dtype=torch.bfloat16, device=device) + out2 = backing2[1 : 1 + m * k].view(m, k) + assert out2.is_contiguous() + assert out2.data_ptr() % 4 == 2 + with pytest.raises(ValueError, match="4-byte aligned"): + _run_moe( + experts, + a_vals=a, + a_scales=scales, + topk_ids=routes, + topk_weights=weights, + tile_m=128, + route_planner="internal", + deterministic=False, + output=out2, + ) + + # Micro backend retains 16-byte pointer assumptions and must fail closed at 4B. + m_micro = 4 + x_micro = x[:m_micro].contiguous() + routes_micro = torch.zeros((m_micro, 1), dtype=torch.int64, device=device) + weights_micro = torch.ones((m_micro, 1), dtype=torch.float32, device=device) + plan_micro = fused_moe.plan_execution( + experts=experts, + capacity=fused_moe.ExecutionCapacity( + max_tokens=m_micro, top_k=1, input_format="bf16" + ), + routing=fused_moe.RoutingSpec(deterministic_output=False), + override=MoeDecodeConfig( + backend="micro", + route_planner="internal", + max_active_clusters=None, + ), + ) + backing4 = torch.empty((m_micro * k + 8,), dtype=torch.bfloat16, device=device) + out4_micro = backing4[2 : 2 + m_micro * k].view(m_micro, k) + assert out4_micro.is_contiguous() + assert out4_micro.data_ptr() % 16 == 4 + session_micro = PreparationSession(compile_workers=0, autotune=False) + box_micro = {} + + def _prep_micro(state): + sc = [ + torch.zeros(spec.nbytes, dtype=spec.dtype, device=device) + for spec in state.scratch.scratch_specs() + ] + b = state.bind( + a=x_micro, + topk_ids=routes_micro, + topk_weights=weights_micro, + output=torch.zeros((m_micro, k), dtype=torch.bfloat16, device=device), + scratch=sc, + input_scales_static=True, + ) + box_micro["state"] = state + box_micro["sc"] = sc + return PreparedCall(run=lambda: state.run(b)) + + session_micro.prepare( + (plan_micro.request(name="micro_align_check", prepare_call=_prep_micro),) + ) + b_bad = box_micro["state"].bind( + a=x_micro, + topk_ids=routes_micro, + topk_weights=weights_micro, + output=out4_micro, + scratch=box_micro["sc"], + input_scales_static=True, + ) + with pytest.raises(ValueError, match="16-byte aligned"): + box_micro["state"].run(b_bad) + + +@pytest.mark.parametrize( + ("intermediate_size", "dynamic_tile_m"), + [(128, 128), (512, 16)], +) +def test_dynamic_monolithic_nvfp4_output_4byte_alignment_fallback( + intermediate_size: int, + dynamic_tile_m: int, +): + """Monolithic NVFP4 dynamic MoE falls back cleanly on 4B/8B/12B mod-16 outputs.""" + device = require_b12x() + e, h, n, m, top_k = 8, 256, intermediate_size, 32, 2 + gen = torch.Generator(device="cpu").manual_seed(441) + w13 = torch.randint(0, 256, (e, 2 * n, h // 2), generator=gen, dtype=torch.uint8).to( + device + ) + w2 = torch.randint(0, 256, (e, h, n // 2), generator=gen, dtype=torch.uint8).to( + device + ) + s13 = ( + torch.empty((e, 2 * n, h // 16), dtype=torch.float32) + .uniform_(0.5, 2.0, generator=gen) + .to(device=device, dtype=torch.float8_e4m3fn) + ) + s2 = ( + torch.empty((e, h, n // 16), dtype=torch.float32) + .uniform_(0.5, 2.0, generator=gen) + .to(device=device, dtype=torch.float8_e4m3fn) + ) + one = torch.ones((e,), dtype=torch.float32, device=device) + wplan = fused_moe.plan_weights( + source=fused_moe.PackedSource(format="modelopt_nvfp4", w13_layout="w13"), + activation=fused_moe.ActivationSpec( + mode="a4", nonlinearity="silu", io_dtype=torch.bfloat16, swiglu_limit=None + ), + geometry=fused_moe.MoEGeometry( + num_experts=e, hidden_size=h, intermediate_size=n + ), + ) + experts = fused_moe.prepare_weights( + plan=wplan, + weights=fused_moe.PackedWeights( + w13=w13, + w2=w2, + w13_block_scales=s13, + w2_block_scales=s2, + w13_global_scales=one, + w2_global_scales=one.clone(), + input_scale=one.clone(), + intermediate_scale=one.clone(), + immutable_input_scales=True, + ), + ) + + x = ( + torch.randn((m, h), generator=gen, dtype=torch.float32) + .mul(0.25) + .to(device=device, dtype=torch.bfloat16) + ) + # First half: single active route per token (order-independent when n == 128). + # Second half: two distinct active routes per token (multi-CTA atomic accumulation). + topk_ids = torch.empty((m, top_k), dtype=torch.int32) + for tok in range(m): + if tok < m // 2: + topk_ids[tok, 0] = tok % e + topk_ids[tok, 1] = -1 + else: + topk_ids[tok, 0] = tok % e + topk_ids[tok, 1] = (tok + 3) % e + topk_ids = topk_ids.to(device=device) + topk_weights = torch.where( + topk_ids >= 0, + torch.full((m, top_k), 0.5, dtype=torch.float32, device=device), + torch.zeros((m, top_k), dtype=torch.float32, device=device), + ) + + plan = fused_moe.plan_execution( + experts=experts, + capacity=fused_moe.ExecutionCapacity( + max_tokens=m, + top_k=top_k, + input_format="bf16", + output_layout="token", + ), + routing=fused_moe.RoutingSpec(deterministic_output=False), + override=MoeDecodeConfig( + backend="dynamic", + route_planner="internal", + max_active_clusters=None, + dynamic_tile_m=dynamic_tile_m, + dynamic_route_mode="grouped", + nvfp4_materialize_intermediate=False, + ), + ) + session = PreparationSession(compile_workers=0, autotune=False) + box = {} + + def _prep(state): + sc = [ + torch.zeros(spec.nbytes, dtype=spec.dtype, device=device) + for spec in state.scratch.scratch_specs() + ] + b = state.bind( + a=x, + topk_ids=topk_ids, + topk_weights=topk_weights, + output=torch.zeros((m, h), dtype=torch.bfloat16, device=device), + scratch=sc, + input_scales_static=True, + ) + box["state"] = state + box["sc"] = sc + return PreparedCall(run=lambda: state.run(b)) + + session.prepare( + ( + plan.request( + name=f"nvfp4_monolithic_4b_align_n{n}_m{dynamic_tile_m}", + prepare_call=_prep, + ), + ) + ) + assert box["state"].config.backend == "dynamic" + assert not box["state"].config.nvfp4_materialize_intermediate + + def _run_with_output(out_buf: torch.Tensor) -> torch.Tensor: + out_buf.fill_(-99.0) + b = box["state"].bind( + a=x, + topk_ids=topk_ids, + topk_weights=topk_weights, + output=out_buf, + scratch=box["sc"], + input_scales_static=True, + ) + box["state"].run(b) + torch.cuda.synchronize() + return out_buf + + ref = _run_with_output(torch.empty((m, h), dtype=torch.bfloat16, device=device)) + assert ref.data_ptr() % 16 == 0 + assert torch.isfinite(ref).all() + assert ref.ne(-99.0).all() + sectors = ref.reshape(m, -1, 8) + assert sectors.ne(0).any(dim=-1).all() + assert sectors[:, 1:].ne(sectors[:, :-1]).any(dim=-1).all() + + backing4 = torch.full((m * h + 16,), -99.0, dtype=torch.bfloat16, device=device) + for elem_offset in (2, 4, 6): + out4 = backing4[elem_offset : elem_offset + m * h].view(m, h) + assert out4.is_contiguous() + assert out4.data_ptr() % 16 == elem_offset * 2 + got4 = _run_with_output(out4) + assert got4.data_ptr() == out4.data_ptr() + assert torch.isfinite(got4).all() + assert got4.ne(0).any() + if n == 128: + # Single intermediate slice + single route per token has one atomic add + # per element, so the 4x bf16x2 fallback must match v4 bit-for-bit. + assert torch.equal( + got4[: m // 2].view(torch.uint16), ref[: m // 2].view(torch.uint16) + ) + cos = F.cosine_similarity( + got4[m // 2 :].float().flatten(), + ref[m // 2 :].float().flatten(), + dim=0, + ) + assert cos.item() > 0.9999 + else: + # Multiple intermediate slices accumulate via concurrent BF16 atomics. + cos = F.cosine_similarity( + got4.float().flatten(), ref.float().flatten(), dim=0 + ) + assert cos.item() > 0.9999 + + # Confirm the CUDA context remains healthy after all 4B/8B/12B launches. + probe = torch.ones((16,), dtype=torch.float32, device=device) + assert float(probe.sum().item()) == 16.0 + + +@pytest.mark.parametrize("deterministic", [False, True]) +def test_w4a8_m128_output_alignment_fallback_and_rejection(deterministic: bool): + """4-byte aligned output falls back cleanly; 2-byte aligned output fails closed.""" + device = require_b12x() + m, k, n, live_rows = 128, 512, 576, 96 + experts, *_ = _build_experts(4, k, n, device, seed=435) + gen = torch.Generator(device=device).manual_seed(436) + x = torch.randn((m, k), generator=gen, dtype=torch.bfloat16, device=device) + a, scales = _quantize_mxfp8(x * 0.25) + routes = torch.full((m, 1), -1, dtype=torch.int64, device=device) + routes[:live_rows] = 0 + weights = routes.ge(0).to(torch.float32) + + ref = _run_moe( + experts, + a_vals=a, + a_scales=scales, + topk_ids=routes, + topk_weights=weights, + tile_m=128, + route_planner="internal", + deterministic=deterministic, + ) + + # Exercise all non-16B 4-byte aligned BF16 offsets (4B, 8B, 12B mod 16). + backing4 = torch.full((m * k + 16,), -99.0, dtype=torch.bfloat16, device=device) + for elem_offset in (2, 4, 6): + out4 = backing4[elem_offset : elem_offset + m * k].view(m, k) + assert out4.is_contiguous() + assert out4.data_ptr() % 16 == elem_offset * 2 + got4 = _run_moe( + experts, + a_vals=a, + a_scales=scales, + topk_ids=routes, + topk_weights=weights, + tile_m=128, + route_planner="internal", + deterministic=deterministic, + output=out4, + ) + assert got4.data_ptr() == out4.data_ptr() + torch.testing.assert_close(got4, ref, rtol=0, atol=0) + + # 2-byte aligned BF16 output view must fail closed with ValueError. + backing2 = torch.empty((m * k + 8,), dtype=torch.bfloat16, device=device) + out2 = backing2[1 : 1 + m * k].view(m, k) + assert out2.is_contiguous() + assert out2.data_ptr() % 4 == 2 + with pytest.raises(ValueError, match="4-byte aligned"): + _run_moe( + experts, + a_vals=a, + a_scales=scales, + topk_ids=routes, + topk_weights=weights, + tile_m=128, + route_planner="internal", + deterministic=deterministic, + output=out2, + ) From c9c5841aa90a9f5205b5278c26c212e81862dbb4 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:39:35 -0600 Subject: [PATCH 2/2] perf(b12x/moe): balance W4A8 M128 tiles with atomic work stealing Why: Static CTA strides leave a long tail with skewed expert routing in SM120 W4A8 M128 prefill MoE. Four row buckets also pad sparse tiles, and scalar epilogue loads add instructions on the M128xN64 path. What: Stacked on PR #161 (d8b6a60e24ed349c05f04e12484df0fbd3e0d56d). - Claim tiles dynamically from atomic counters in W4A8MaterializedPhase1Kernel and W4A8MaterializedPhase2Kernel, group N64 tiles in strips of three for L2 reuse, dispatch to six row buckets (16, 32, 48, 64, 96, 128), and vectorize the M128xN64 up-projection epilogue's shared loads. - Guarantee both work-stealing counters (task_head and producers_done_count) are zeroed across every launch and CUDA-graph replay path: - Zero task_head and p2_task_head in _prequant_route_init_zero_kernel and _dynamic_route_plan_kernel (plus matching _preparation.py compile_dynamic_route_plan warmups) and under volatile_launch_state when external_route_plan is disabled. - Reset p2_task_head in W4A8MaterializedPhase1Kernel and symmetrically reset p1_task_head in W4A8MaterializedPhase2Kernel. - Guard Phase 2 dynamic work stealing on fused_groups == 1 (with explicit assertions against tile_m == 128 and fused_groups > 1). - Skip initial work-steal atomic increments when task_tail == 0 in both Phase 1 and Phase 2 while still executing the opposite-phase reset. - Advance the integration.tp_moe.dynamic compile spec from 23 to 24. - Add CPU swizzle/bucket/reset-contract tests, direct Phase 1/2 work-stealing and empty-launch tests, Triton route-plan counter-reset tests, and end-to-end poisoned-scratch replay tests covering mxfp8+triton+M128, bf16+triton+M16, and bf16+internal+M128 in tests/experimental/b12x/moe/test_w4a8_prefill_m128.py. Result: Single-GPU NVIDIA GeForce RTX 5090 (SM120) CUDA-graph comparison at M=8192, H=5120, E=384, k=6, N=576, Zipf 1.1 with the Triton route planner and inline scales (including the PR #161 epilogue prerequisite) previously recorded 2697.8 -> 2424.5 us mean median, with zero BF16 bit differences across 41,943,040 deterministic outputs versus M64. Evidence: Verified locally on single-GPU RTX 5090 (SM120, PyTorch 2.14.1+cu132, CUTLASS DSL 4.8.1) from exact git archive HEAD (multi-GPU / TP4 not exercised here): - tests/experimental/b12x/moe/test_w4a8_prefill_m128.py: 47 passed, 0 failed (including test_w4a8_m128_validation_and_heuristics, test_w4a8_m128_compute_m96_and_no_tail_barrier_invariants, test_w4a8_m128_worksteal_swizzle_buckets_and_reset_contracts, test_w4a8_m128_triton_route_plan_kernels_zero_worksteal_counters, test_w4a8_m128_phase1_worksteal_n3_swizzle_and_empty_direct, test_w4a8_m128_phase2_worksteal_counter_reset_and_empty_direct, test_w4a8_m128_phase2_alignment_fallback_and_compute_m96_direct [False/True], test_w4a8_m128_output_2byte_alignment_rejected, test_dynamic_monolithic_nvfp4_output_4byte_alignment_fallback [128-128, 512-16], test_w4a8_m128_output_alignment_fallback_and_rejection [False/True], and test_w4a8_m128_poisoned_scratch_replay across mxfp8-triton-m128, bf16-triton-m16, and bf16-internal-m128) - compile_dynamic_route_plan warmups: 3/3 passed for (preq=False, full=False), (preq=True, full=False), and (preq=True, full=True) - ruff 0.12.8 check clean across all 6 touched files; git merge-tree --write-tree 335459b2 HEAD clean; git diff --check clean. Discord: Dooner Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> --- .../moe/_shared/kernels/dynamic/kernel.py | 4 + .../b12x/moe/_shared/kernels/w4a8_phase1.py | 119 ++- .../b12x/moe/_shared/kernels/w4a8_phase2.py | 51 +- .../experimental/b12x/moe/fused_moe/_impl.py | 16 +- .../b12x/moe/fused_moe/_preparation.py | 4 + .../b12x/moe/test_w4a8_prefill_m128.py | 867 ++++++++++++++++++ 6 files changed, 1039 insertions(+), 22 deletions(-) diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py b/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py index 141daccb5bd..f5754a5bd36 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/dynamic/kernel.py @@ -2439,6 +2439,8 @@ def __call__( Int32(b_w13.shape[0]) // Int32(256), max_active_clusters, stream, + task_head=task_head, + p2_task_head=producers_done_count, ) if cutlass.const_expr(self.external_materialized_fc2): if cutlass.const_expr(self.nvfp4_split_materialized): @@ -2477,6 +2479,8 @@ def __call__( max_active_clusters, Int32(0), stream, + task_head=producers_done_count, + p1_task_head=task_head, ) @cute.kernel diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py index 6fce5957ec9..981a24f0308 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase1.py @@ -63,6 +63,7 @@ def _cp_async4_l2_evict_first( ld_shared_v2_u32, ld_shared_v4_u32, shared_ptr_to_u32, + u32_as_f32, ) from b12x._lib.intrinsics.mma import ( e2m1x8_to_qmma_e2m1x8, @@ -71,6 +72,7 @@ def _cp_async4_l2_evict_first( mxfp8_mma_m16n8k32_f32_e4m3, ) from b12x._lib.intrinsics.atomics import ( + atomic_add_global_i32, ld_shared_bf16_to_f32, ld_shared_u32, st_shared_u32, @@ -183,6 +185,9 @@ def __init__( # 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 self.shared_words = (total_shared_bytes + 3) // 4 self.source_tile_m = int(source_tile_m) self.source_halves = self.source_tile_m // self.tile_m @@ -233,6 +238,8 @@ def __call__( packed_w13_tiles: cutlass.Int32, max_active_clusters: cutlass.Int32, stream: cuda.CUstream, + task_head: cute.Tensor | None = None, + p2_task_head: cute.Tensor | None = None, ): if cutlass.const_expr(self.cta_budget == 3): assert ( @@ -260,6 +267,8 @@ def __call__( input_k128_tiles, intermediate_tiles, packed_w13_tiles, + task_head, + p2_task_head, ).launch( grid=(1, 1, max_active_clusters * Int32(self.launch_cta_budget)), block=[self.threads_per_cta, 1, 1], @@ -1807,10 +1816,11 @@ def _run_task( if cutlass.const_expr(is_m128_n64): subgroup_lane = tid & Int32(3) rows_per_iter = self.threads_per_cta // 4 + row_iters = (compute_m + rows_per_iter - 1) // rows_per_iter intermediate_u16 = cute.recast_tensor(intermediate_u32, Uint16) physical_tile = output_tile >> Int32(1) packed_half = output_tile & Int32(1) - for row_iter in cutlass.range_constexpr(compute_m // rows_per_iter): + for row_iter in cutlass.range_constexpr(row_iters): row = (tid >> Int32(2)) + Int32(row_iter * rows_per_iter) warp_first_row = warp_idx * Int32(8) + Int32(row_iter * rows_per_iter) if warp_first_row < valid_rows: @@ -1818,20 +1828,29 @@ def _run_task( for block in cutlass.range_constexpr(2): values = cute.make_rmem_tensor((8,), cutlass.Float32) block_max = cutlass.Float32(0.0) - for elem in cutlass.range_constexpr(8): - value = cutlass.Float32(0.0) - if row < valid_rows: - value = ld_shared_bf16_to_f32( - epilogue_base - + ( - row * Int32(64) - + Int32(block * 32 + elem) - + subgroup_lane * Int32(8) - ) - * Int32(2) + if row < valid_rows: + w0, w1, w2, w3 = ld_shared_v4_u32( + epilogue_base + + ( + row * Int32(64) + + Int32(block * 32) + + subgroup_lane * Int32(8) ) - values[elem] = value - block_max = fmax_f32(block_max, fabs_f32(value)) + * Int32(2) + ) + values[0] = u32_as_f32(w0 << Uint32(16)) + values[1] = u32_as_f32(w0 & Uint32(0xFFFF0000)) + values[2] = u32_as_f32(w1 << Uint32(16)) + values[3] = u32_as_f32(w1 & Uint32(0xFFFF0000)) + values[4] = u32_as_f32(w2 << Uint32(16)) + values[5] = u32_as_f32(w2 & Uint32(0xFFFF0000)) + values[6] = u32_as_f32(w3 << Uint32(16)) + values[7] = u32_as_f32(w3 & Uint32(0xFFFF0000)) + for elem in cutlass.range_constexpr(8): + block_max = fmax_f32(block_max, fabs_f32(values[elem])) + else: + for elem in cutlass.range_constexpr(8): + values[elem] = cutlass.Float32(0.0) for shift in cutlass.range_constexpr(2): block_max = fmax_f32( block_max, @@ -2007,12 +2026,17 @@ def kernel( input_k128_tiles: cutlass.Int32, intermediate_tiles: cutlass.Int32, packed_w13_tiles: cutlass.Int32, + task_head: cute.Tensor | None = None, + p2_task_head: cute.Tensor | None = None, ): tidx, _, _ = cute.arch.thread_idx() _, _, bidz = cute.arch.block_idx() _, _, gdimz = cute.arch.grid_dim() tid = Int32(tidx) warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + if cutlass.const_expr(p2_task_head is not None): + if Int32(bidz) == Int32(0) and tid == Int32(0): + p2_task_head[Int32(0)] = Int32(0) smem = cutlass.utils.SmemAllocator() @@ -2047,11 +2071,50 @@ class Storage: output_tiles = intermediate_tiles num_experts = Int32(expert_tile_base.shape[0] - 1) source_m_tiles = expert_tile_base[num_experts].to(Int32) - task_tail = source_m_tiles * Int32(self.source_halves) * output_tiles + total_source_halves = source_m_tiles * Int32(self.source_halves) + task_tail = total_source_halves * output_tiles + use_dyn = self.fast_m128_src and task_head is not None + slot_smem = smem_base + Int32(self.slot_smem_offset) task_slot = Int32(bidz) + if cutlass.const_expr(use_dyn): + if task_tail > Int32(0): + if tid == Int32(0): + st_shared_u32( + slot_smem, + Uint32( + atomic_add_global_i32( + get_ptr_as_int64(task_head, Int32(0)), Int32(1) + ) + ), + ) + cute.arch.sync_threads() + task_slot = ld_shared_u32(slot_smem).to(Int32) + else: + task_slot = task_tail while task_slot < task_tail: - output_tile = task_slot % output_tiles - source_half = task_slot // output_tiles + output_tile = Int32(0) + source_half = Int32(0) + if cutlass.const_expr(self.fast_m128_src): + # Strip N64 output tiles in groups of 3 so concurrent CTAs share + # hot-expert w13 weights and A rows across L2 while dynamic + # work-stealing eliminates Zipf M-tile tail imbalance. + group_n = Int32(3) + full_strips = output_tiles // group_n + strip_tasks = total_source_halves * group_n + full_strip_tasks = full_strips * strip_tasks + if task_slot < full_strip_tasks: + strip_idx = task_slot // strip_tasks + rem = task_slot % strip_tasks + output_tile = strip_idx * group_n + (rem % group_n) + source_half = rem // group_n + else: + rem_n = cutlass.max(output_tiles - full_strips * group_n, Int32(1)) + rem = task_slot - full_strip_tasks + output_tile = full_strips * group_n + (rem % rem_n) + source_half = rem // rem_n + else: + output_tile = task_slot % output_tiles + source_half = task_slot // output_tiles m_half = source_half % Int32(self.source_halves) source_m_tile = source_half // Int32(self.source_halves) phase1_meta = source_m_tile * intermediate_tiles @@ -2097,8 +2160,12 @@ class Storage: else: self._run_task(*task_args, 16) elif cutlass.const_expr(self.tile_m == 128): - if valid_rows <= Int32(32): + if valid_rows <= Int32(16): + self._run_task(*task_args, 16) + elif valid_rows <= Int32(32): self._run_task(*task_args, 32) + elif valid_rows <= Int32(48): + self._run_task(*task_args, 48) elif valid_rows <= Int32(64): self._run_task(*task_args, 64) elif valid_rows <= Int32(96): @@ -2119,7 +2186,21 @@ class Storage: self._run_task(*task_args, self.tile_m) else: self._run_task(*task_args, self.tile_m) - task_slot += Int32(gdimz) + if cutlass.const_expr(use_dyn): + cute.arch.sync_threads() + if tid == Int32(0): + st_shared_u32( + slot_smem, + Uint32( + atomic_add_global_i32( + get_ptr_as_int64(task_head, Int32(0)), Int32(1) + ) + ), + ) + cute.arch.sync_threads() + task_slot = ld_shared_u32(slot_smem).to(Int32) + else: + task_slot += Int32(gdimz) __all__ = ["W4A8MaterializedPhase1Kernel"] diff --git a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py index e1f36328d82..803a2ea8e9a 100644 --- a/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py +++ b/flashinfer/experimental/b12x/moe/_shared/kernels/w4a8_phase2.py @@ -33,6 +33,7 @@ ) from b12x._lib.intrinsics.mma import e2m1x8_to_qmma_e2m1x8, mxfp8_mma_m16n8k32_f32_e2m1 from b12x._lib.intrinsics.atomics import ( + atomic_add_global_i32, ld_shared_u32, red_add_global_bf16x2, red_add_global_v4_bf16x2, @@ -120,6 +121,9 @@ def __init__( self.num_warps = 4 self.stages = 3 self.launch_cta_budget = 2 + assert self.fused_groups == 1, ( + "M128 phase 2 work stealing requires single-group CTAs" + ) else: self.tile_m = type(self).tile_m self.tile_k = type(self).tile_k @@ -195,6 +199,8 @@ def __call__( max_active_clusters: cutlass.Int32, num_pairs: cutlass.Int32, stream: cuda.CUstream, + task_head: cute.Tensor | None = None, + p1_task_head: cute.Tensor | None = None, ): # Fused route groups own disjoint CSF slots and decoded-row scratch. assert ( @@ -202,6 +208,7 @@ def __call__( or self.fused_topk == 0 or (self.direct_routes and self.fused_groups == 2 and self.num_warps == 4) ) + assert not (self.tile_m == 128 and self.fused_groups > 1) grid_z = max_active_clusters * Int32(self.launch_cta_budget) if cutlass.const_expr(self.direct_routes): grid_z = num_pairs * packed_output_tiles * Int32(256 // self.tile_n) @@ -224,6 +231,8 @@ def __call__( intermediate_tiles, packed_output_tiles, num_pairs, + task_head, + p1_task_head, ).launch( grid=(1, 1, grid_z), block=[self.threads_per_cta * self.fused_groups, 1, 1], @@ -1626,12 +1635,17 @@ def kernel( intermediate_tiles: cutlass.Int32, packed_output_tiles: cutlass.Int32, num_pairs: cutlass.Int32, + task_head: cute.Tensor | None = None, + p1_task_head: cute.Tensor | None = None, ): tidx, _, _ = cute.arch.thread_idx() _, _, bidz = cute.arch.block_idx() _, _, gdimz = cute.arch.grid_dim() tid = Int32(tidx) warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + if cutlass.const_expr(p1_task_head is not None): + if Int32(bidz) == Int32(0) and tid == Int32(0): + p1_task_head[Int32(0)] = Int32(0) smem = cutlass.utils.SmemAllocator() @@ -1816,7 +1830,27 @@ class Storage: source_m_tiles = expert_tile_base[num_experts].to(Int32) total_source_halves = source_m_tiles * Int32(self.source_halves) task_tail = total_source_halves * output_tiles + use_dyn = ( + self.tile_m == 128 and self.fused_groups == 1 and task_head is not None + ) + slot_shared = None + if cutlass.const_expr(use_dyn): + slot_shared = smem.allocate_tensor( + cutlass.Int32, + cute.make_layout((1,)), + byte_alignment=16, + ) task_slot = Int32(bidz) + if cutlass.const_expr(use_dyn): + if task_tail > Int32(0): + if tid == Int32(0): + slot_shared[Int32(0)] = atomic_add_global_i32( + get_ptr_as_int64(task_head, Int32(0)), Int32(1) + ) + cute.arch.sync_threads() + task_slot = slot_shared[Int32(0)] + else: + task_slot = task_tail while task_slot < task_tail: output_tile = Int32(0) source_half = Int32(0) @@ -1884,8 +1918,12 @@ class Storage: else: self._run_task(*task_args) elif cutlass.const_expr(self.tile_m == 128): - if valid_rows <= Int32(32): + if valid_rows <= Int32(16): + self._run_task_m128(*task_args, 16) + elif valid_rows <= Int32(32): self._run_task_m128(*task_args, 32) + elif valid_rows <= Int32(48): + self._run_task_m128(*task_args, 48) elif valid_rows <= Int32(64): self._run_task_m128(*task_args, 64) elif valid_rows <= Int32(96): @@ -1894,7 +1932,16 @@ class Storage: self._run_task_m128(*task_args, 128) else: self._run_task(*task_args) - task_slot += Int32(gdimz) + if cutlass.const_expr(use_dyn): + cute.arch.sync_threads() + if tid == Int32(0): + slot_shared[Int32(0)] = atomic_add_global_i32( + get_ptr_as_int64(task_head, Int32(0)), Int32(1) + ) + cute.arch.sync_threads() + task_slot = slot_shared[Int32(0)] + else: + task_slot += Int32(gdimz) __all__ = ["W4A8MaterializedPhase2Kernel"] diff --git a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py index 470af81b610..ff15722100a 100644 --- a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py +++ b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py @@ -2173,6 +2173,8 @@ def _dynamic_route_plan_kernel( expert_tile_base, barrier_count, barrier_epoch, + task_head, + p2_task_head, live_routes, NUM_EXPERTS: tl.constexpr, TILE_M: tl.constexpr, @@ -2182,6 +2184,8 @@ def _dynamic_route_plan_kernel( """Initialize grouped routing and its resident-grid barrier in one CTA.""" tl.store(barrier_count, 0) tl.store(barrier_epoch, 0) + tl.store(task_head, 0) + tl.store(p2_task_head, 0) experts = tl.arange(0, BLOCK_E) expert_mask = experts < NUM_EXPERTS tl.store(row_counts + experts, 0, mask=expert_mask) @@ -2212,6 +2216,8 @@ def _prequant_route_init_zero_kernel( expert_write_rows, barrier_count, barrier_epoch, + task_head, + p2_task_head, NUM_EXPERTS: tl.constexpr, BLOCK_E: tl.constexpr, RESET_BARRIER: tl.constexpr, @@ -2221,6 +2227,8 @@ def _prequant_route_init_zero_kernel( mask = experts < NUM_EXPERTS tl.store(row_counts + experts, 0, mask=mask) tl.store(expert_write_rows + experts, 0, mask=mask) + tl.store(task_head, 0) + tl.store(p2_task_head, 0) if RESET_BARRIER: tl.store(barrier_count, 0) tl.store(barrier_epoch, 0) @@ -12486,7 +12494,7 @@ def _get_dynamic_kernel( ), compile_spec=KernelCompileSpec.from_key( "integration.tp_moe.dynamic", - 23, + 24, cache_key, ), dsl_compile_options=dsl_compile_options, @@ -12813,6 +12821,8 @@ def _launch_dynamic_flat( if volatile_launch_state and not external_route_plan: barrier_count.zero_() barrier_epoch.zero_() + task_head.zero_() + producers_done_count.zero_() if external_route_plan: block_e = 1 << (int(E) - 1).bit_length() @@ -12835,6 +12845,8 @@ def _launch_dynamic_flat( expert_write_rows, barrier_count, barrier_epoch, + task_head, + producers_done_count, NUM_EXPERTS=E, BLOCK_E=block_e, RESET_BARRIER=not full_route_plan, @@ -12905,6 +12917,8 @@ def _launch_dynamic_flat( expert_tile_base, barrier_count, barrier_epoch, + task_head, + producers_done_count, routed_rows, NUM_EXPERTS=E, TILE_M=selected_tile_m, diff --git a/flashinfer/experimental/b12x/moe/fused_moe/_preparation.py b/flashinfer/experimental/b12x/moe/fused_moe/_preparation.py index 91d384474e2..e95c80c8c03 100644 --- a/flashinfer/experimental/b12x/moe/fused_moe/_preparation.py +++ b/flashinfer/experimental/b12x/moe/fused_moe/_preparation.py @@ -1957,6 +1957,8 @@ def compile_dynamic_route_plan(payload, ordinal): MockTensor(torch.int32, (num_experts,)), MockTensor(torch.int32, (1,)), MockTensor(torch.int32, (1,)), + MockTensor(torch.int32, (1,)), + MockTensor(torch.int32, (1,)), NUM_EXPERTS=num_experts, BLOCK_E=block_e, RESET_BARRIER=not full_route_plan, @@ -2018,6 +2020,8 @@ def compile_dynamic_route_plan(payload, ordinal): MockTensor(torch.int32, (num_experts + 1,)), MockTensor(torch.int32, (1,)), MockTensor(torch.int32, (1,)), + MockTensor(torch.int32, (1,)), + MockTensor(torch.int32, (1,)), rows, NUM_EXPERTS=num_experts, TILE_M=tile_m, diff --git a/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py b/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py index 08c9c4fd341..79b7b23149f 100644 --- a/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py +++ b/tests/experimental/b12x/moe/test_w4a8_prefill_m128.py @@ -1426,3 +1426,870 @@ def test_w4a8_m128_output_alignment_fallback_and_rejection(deterministic: bool): deterministic=deterministic, output=out2, ) + + +@pytest.mark.parametrize("max_active_clusters", [2, 64]) +def test_w4a8_m128_internal_replay_covers_short_strip_and_empty_routes( + max_active_clusters, +): + device = require_b12x() + m, k, n, expert_count = 160, 512, 704, 4 + experts, *_ = _build_experts(expert_count, k, n, device, seed=700) + gen = torch.Generator(device=device).manual_seed(701) + # Four expert tiles yield 44 up-projection tasks across N64 strips of + # three, with a two-tile final strip. The grid limits straddle 44. + counts = (16, 17, 48, 49) + nonempty = torch.repeat_interleave( + torch.arange(expert_count, device=device), + torch.tensor(counts, device=device), + ) + assert (max_active_clusters > expert_count * (n // 64)) == ( + max_active_clusters == 64 + ) + ids = torch.full((m, 1), -1, dtype=torch.int64, device=device) + ids[: nonempty.numel(), 0] = nonempty + weights = ids.ge(0).to(torch.float32) + a, scales = _quantize_mxfp8( + torch.randn((m, k), generator=gen, dtype=torch.bfloat16, device=device) * 0.25 + ) + out = torch.empty((m, k), dtype=torch.bfloat16, device=device) + + plan = fused_moe.plan_execution( + experts=experts, + capacity=fused_moe.ExecutionCapacity( + max_tokens=m, top_k=1, input_format="mxfp8" + ), + routing=fused_moe.RoutingSpec(deterministic_output=True), + override=MoeDecodeConfig( + backend="dynamic", + route_planner="internal", + max_active_clusters=max_active_clusters, + dynamic_tile_m=128, + dynamic_route_mode="grouped", + ), + ) + session = PreparationSession(compile_workers=0, autotune=False) + prepared = {} + + def prepare(state): + scratch = [ + torch.zeros(spec.nbytes, dtype=spec.dtype, device=device) + for spec in state.scratch.scratch_specs() + ] + binding = state.bind( + a=a, + a_scales=scales, + topk_ids=ids, + topk_weights=weights, + output=out, + scratch=scratch, + input_scales_static=True, + ) + call = PreparedCall(run=lambda: state.run(binding)) + prepared["run"] = call.run + return call + + session.prepare((plan.request(name="internal_m128", prepare_call=prepare),)) + run = prepared["run"] + run() + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with session.capture(), torch.cuda.graph(graph): + run() + try: + for step in range(5): + x = torch.randn((m, k), generator=gen, dtype=torch.bfloat16, device=device) + next_a, next_scales = _quantize_mxfp8(x * 0.25) + a.copy_(next_a) + scales.copy_(next_scales) + ids.fill_(-1) + if step % 2 == 0: + ids[: nonempty.numel(), 0] = (nonempty + step) % expert_count + weights.copy_(ids.ge(0)) + out.fill_(float("nan")) + ref = _run_moe( + experts, + a_vals=a, + a_scales=scales, + topk_ids=ids, + topk_weights=weights, + tile_m=64, + route_planner="internal", + deterministic=True, + ) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(out, ref, rtol=0, atol=0) + if step % 2: + assert torch.count_nonzero(ref).item() == 0 + else: + last_rows = slice(nonempty.numel() - counts[-1], nonempty.numel()) + assert ref[last_rows, -128:].ne(0).any() + dropped = out.clone() + dropped[last_rows, -128:] = 0 + with pytest.raises(AssertionError): + torch.testing.assert_close(dropped, ref, rtol=0, atol=0) + finally: + graph.reset() + session.close() + + +def test_w4a8_m128_worksteal_swizzle_buckets_and_reset_contracts(): + """CPU-only verification of N3/N8 strip swizzles, compute_m buckets, and reset contracts.""" + import inspect + + from b12x.moe._shared.kernels.w4a8_phase1 import W4A8MaterializedPhase1Kernel + from b12x.moe._shared.kernels.w4a8_phase2 import W4A8MaterializedPhase2Kernel + from b12x.moe.fused_moe import _impl + + def _strip_swizzle( + task_slot: int, total_source_halves: int, output_tiles: int, group_n: int + ): + full_strips = output_tiles // group_n + strip_tasks = total_source_halves * group_n + full_strip_tasks = full_strips * strip_tasks + if task_slot < full_strip_tasks: + strip_idx = task_slot // strip_tasks + rem = task_slot % strip_tasks + return strip_idx * group_n + (rem % group_n), rem // group_n + rem_n = max(output_tiles - full_strips * group_n, 1) + rem = task_slot - full_strip_tasks + return full_strips * group_n + (rem % rem_n), rem // rem_n + + # Verify N3 (Phase 1, including output_tiles < 3) and N8 (Phase 2) are exact bijections. + for group_n, tile_counts in ( + (3, (1, 2, 3, 4, 5, 9, 11, 12)), + (8, (1, 2, 7, 8, 9, 16, 17)), + ): + for output_tiles in tile_counts: + for total_source_halves in (1, 2, 5): + expected = { + (ot, sh) + for ot in range(output_tiles) + for sh in range(total_source_halves) + } + got = [ + _strip_swizzle(slot, total_source_halves, output_tiles, group_n) + for slot in range(total_source_halves * output_tiles) + ] + assert len(got) == len(expected) + assert set(got) == expected + + # Verify all six M128 compute_m buckets in Phase 1 and Phase 2 plus SMEM/fused_groups invariants. + for n64_repacked in (False, True): + p1 = W4A8MaterializedPhase1Kernel( + source_tile_m=128, n64_repacked=n64_repacked, num_topk=1 + ) + p2 = W4A8MaterializedPhase2Kernel(source_tile_m=128, n64_repacked=n64_repacked) + assert p1.fast_m128_src and p1.tile_m == 128 and p1.tile_n == 64 + assert p1.slot_smem_offset >= p1.csf_warp_scratch_offset + p1.num_warps * 128 + assert p1.shared_words * 4 >= p1.slot_smem_offset + 16 + assert p2.tile_m == 128 and p2.tile_n == 128 and p2.fused_groups == 1 + + rows_per_iter = p1.threads_per_cta // 4 + for compute_m in (16, 32, 48, 64, 96, 128): + assert compute_m % 16 == 0 and compute_m % 8 == 0 + row_iters = (compute_m + rows_per_iter - 1) // rows_per_iter + covered_p1 = { + (tid >> 2) + r * rows_per_iter + for r in range(row_iters) + for tid in range(p1.threads_per_cta) + if (tid >> 2) + r * rows_per_iter < compute_m + } + assert covered_p1 == set(range(compute_m)) + rows_per_warp = compute_m // 4 + assert rows_per_warp % 2 == 0 + covered_p2 = { + w * rows_per_warp + rp * 2 + (lane >> 4) + for w in range(p2.num_warps) + for rp in range(rows_per_warp // 2) + for lane in range(32) + } + assert covered_p2 == set(range(compute_m)) + assert compute_m * (272 + 4 + 4) <= p2.shared_bytes + + # Verify counter-reset parameter contracts across route planners and phase kernels. + assert "task_head" in _impl._dynamic_route_plan_kernel.arg_names + assert "p2_task_head" in _impl._dynamic_route_plan_kernel.arg_names + assert "task_head" in _impl._prequant_route_init_zero_kernel.arg_names + assert "p2_task_head" in _impl._prequant_route_init_zero_kernel.arg_names + p1_params = inspect.signature(W4A8MaterializedPhase1Kernel.__call__).parameters + p2_params = inspect.signature(W4A8MaterializedPhase2Kernel.__call__).parameters + assert "task_head" in p1_params and "p2_task_head" in p1_params + assert "task_head" in p2_params and "p1_task_head" in p2_params + + +def test_w4a8_m128_triton_route_plan_kernels_zero_worksteal_counters(): + """Verify both external Triton route-plan kernels zero poisoned task_head and p2_task_head.""" + from b12x.moe.fused_moe import _impl, _preparation + + device = require_b12x() + num_experts = 8 + block_e = 8 + tile_m = 128 + + # Warmup paths in _preparation.py must match both Triton kernel signatures. + _preparation.compile_dynamic_route_plan( + { + "num_experts": num_experts, + "tile_m": tile_m, + "ids_dtype": "int32", + "prequantized_input": False, + }, + device.index or 0, + ) + _preparation.compile_dynamic_route_plan( + { + "num_experts": num_experts, + "tile_m": tile_m, + "ids_dtype": "int32", + "prequantized_input": True, + "num_topk": 2, + "full_route_plan": True, + "store_pair_idx": True, + }, + device.index or 0, + ) + + topk_ids = torch.tensor([0, 0, 3, -1, 7, 3], dtype=torch.int32, device=device) + row_counts = torch.full((num_experts,), 99, dtype=torch.int32, device=device) + expert_write_rows = torch.full((num_experts,), 88, dtype=torch.int32, device=device) + expert_tile_base = torch.full( + (num_experts + 1,), -1, dtype=torch.int32, device=device + ) + barrier_count = torch.tensor([55], dtype=torch.int32, device=device) + barrier_epoch = torch.tensor([44], dtype=torch.int32, device=device) + task_head = torch.tensor([999], dtype=torch.int32, device=device) + p2_task_head = torch.tensor([777], dtype=torch.int32, device=device) + + _impl._dynamic_route_plan_kernel[(1,)]( + topk_ids, + row_counts, + expert_tile_base, + barrier_count, + barrier_epoch, + task_head, + p2_task_head, + topk_ids.numel(), + NUM_EXPERTS=num_experts, + TILE_M=tile_m, + BLOCK_E=block_e, + BLOCK_ROUTES=_impl._DYNAMIC_EXTERNAL_ROUTE_PLAN_MAX_ROWS, + num_warps=8, + ) + torch.cuda.synchronize() + assert barrier_count.item() == 0 + assert barrier_epoch.item() == 0 + assert task_head.item() == 0 + assert p2_task_head.item() == 0 + assert expert_tile_base[-1].item() == 3 # experts 0, 3, 7 each get 1 tile + + for reset_barrier in (False, True): + barrier_count.fill_(55) + barrier_epoch.fill_(44) + task_head.fill_(999) + p2_task_head.fill_(777) + _impl._prequant_route_init_zero_kernel[(1,)]( + row_counts, + expert_write_rows, + barrier_count, + barrier_epoch, + task_head, + p2_task_head, + NUM_EXPERTS=num_experts, + BLOCK_E=block_e, + RESET_BARRIER=reset_barrier, + num_warps=4, + ) + torch.cuda.synchronize() + assert task_head.item() == 0 + assert p2_task_head.item() == 0 + if reset_barrier: + assert barrier_count.item() == 0 + assert barrier_epoch.item() == 0 + + +@pytest.mark.parametrize(("inter_tiles", "n64_tail"), [(1, False), (6, True)]) +def test_w4a8_m128_phase1_worksteal_n3_swizzle_and_empty_direct( + inter_tiles: int, n64_tail: bool +): + """Direct SM120 Phase-1 work-stealing across output_tiles < 3 and = 11, all 6 buckets, and empty.""" + import cutlass + import cutlass.cute as cute + from cutlass.cute.runtime import make_ptr + + from b12x._lib.utils.device import current_cuda_stream + from b12x.moe._shared.kernels.w4a8_phase1 import W4A8MaterializedPhase1Kernel + + device = require_b12x() + E = 6 + counts = (16, 17, 48, 64, 96, 128) + input_k128_tiles = 2 + packed_w13_tiles = inter_tiles + rows_capacity = E * 128 + words_per_row = inter_tiles * 32 + inter_total_words = rows_capacity * words_per_row + inter_tiles * rows_capacity + + gen = torch.Generator(device="cpu").manual_seed(710 + inter_tiles) + packed_a = ( + torch.randint( + 0x30, + 0x48, + (rows_capacity * input_k128_tiles * 32 * 4,), + generator=gen, + dtype=torch.uint8, + ) + .view(torch.uint32) + .to(device) + ) + scale_storage = torch.full( + (rows_capacity * input_k128_tiles * 4,), + 0x7F, + dtype=torch.uint8, + device=device, + ) + w13_rp = torch.randint( + 0, + 1 << 30, + (E * packed_w13_tiles * input_k128_tiles * 4096,), + generator=gen, + dtype=torch.int32, + ).to(device=device, dtype=torch.uint32) + w13_sfb_rp = torch.full( + (E * packed_w13_tiles * input_k128_tiles * 256,), + 0x7F7F7F7F, + dtype=torch.int32, + device=device, + ).to(torch.uint32) + token_map = torch.arange(rows_capacity, dtype=torch.int32, device=device) + token_weights = torch.ones((rows_capacity,), dtype=torch.float32, device=device) + task_expert = torch.repeat_interleave( + torch.arange(E, dtype=torch.int32, device=device), inter_tiles + ) + task_valid = torch.repeat_interleave( + torch.tensor(counts, dtype=torch.int32, device=device), inter_tiles + ) + expert_base = torch.arange(E + 1, dtype=torch.int32, device=device) + alpha = torch.ones((E,), dtype=torch.float32, device=device) + input_gs = torch.ones((E,), dtype=torch.float32, device=device) + lut = torch.zeros((1,), dtype=torch.uint8, device=device) + rot = torch.zeros((1,), dtype=torch.float16, device=device) + task_head = torch.zeros((1,), dtype=torch.int32, device=device) + p2_task_head = torch.zeros((1,), dtype=torch.int32, device=device) + + p1 = W4A8MaterializedPhase1Kernel( + source_tile_m=128, + n64_repacked=False, + n64_tail=n64_tail, + num_topk=1, + ) + + def _p(dtype, t, align=16): + return make_ptr( + dtype, t.data_ptr(), cute.AddressSpace.gmem, assumed_align=align + ) + + def _compile(use_dyn: bool): + @cute.jit + def _wrap( + pa_p, + sc_p, + w13_p, + sfb_p, + inter_p, + tm_p, + tw_p, + te_p, + tv_p, + eb_p, + al_p, + gs_p, + lut_p, + rot_p, + th_p, + p2h_p, + stream, + ): + pa_t = cute.make_tensor( + pa_p, cute.make_layout((packed_a.numel(),), stride=(1,)) + ) + sc_t = cute.make_tensor( + sc_p, cute.make_layout((scale_storage.numel(),), stride=(1,)) + ) + w13_t = cute.make_tensor( + w13_p, cute.make_layout((w13_rp.numel(),), stride=(1,)) + ) + sfb_t = cute.make_tensor( + sfb_p, cute.make_layout((w13_sfb_rp.numel(),), stride=(1,)) + ) + inter_t = cute.make_tensor( + inter_p, cute.make_layout((inter_total_words,), stride=(1,)) + ) + tm_t = cute.make_tensor( + tm_p, cute.make_layout((rows_capacity,), stride=(1,)) + ) + tw_t = cute.make_tensor( + tw_p, cute.make_layout((rows_capacity,), stride=(1,)) + ) + te_t = cute.make_tensor( + te_p, cute.make_layout((task_expert.numel(),), stride=(1,)) + ) + tv_t = cute.make_tensor( + tv_p, cute.make_layout((task_valid.numel(),), stride=(1,)) + ) + eb_t = cute.make_tensor(eb_p, cute.make_layout((E + 1,), stride=(1,))) + al_t = cute.make_tensor(al_p, cute.make_layout((E,), stride=(1,))) + gs_t = cute.make_tensor(gs_p, cute.make_layout((E,), stride=(1,))) + lut_t = cute.make_tensor(lut_p, cute.make_layout((1,), stride=(1,))) + rot_t = cute.make_tensor(rot_p, cute.make_layout((1,), stride=(1,))) + th_t = cute.make_tensor(th_p, cute.make_layout((1,), stride=(1,))) + p2h_t = cute.make_tensor(p2h_p, cute.make_layout((1,), stride=(1,))) + p1( + pa_t, + sc_t, + w13_t, + sfb_t, + inter_t, + tm_t, + tw_t, + te_t, + tv_t, + eb_t, + al_t, + gs_t, + lut_t, + rot_t, + cutlass.Int32(input_k128_tiles), + cutlass.Int32(inter_tiles), + cutlass.Int32(packed_w13_tiles), + cutlass.Int32(4), + stream, + task_head=th_t if use_dyn else None, + p2_task_head=p2h_t if use_dyn else None, + ) + + out_tmp = torch.zeros((inter_total_words,), dtype=torch.uint32, device=device) + return cute.compile( + _wrap, + _p(cutlass.Uint32, packed_a), + _p(cutlass.Uint8, scale_storage), + _p(cutlass.Uint32, w13_rp), + _p(cutlass.Uint32, w13_sfb_rp), + _p(cutlass.Uint32, out_tmp), + _p(cutlass.Int32, token_map, 4), + _p(cutlass.Float32, token_weights, 4), + _p(cutlass.Int32, task_expert, 4), + _p(cutlass.Int32, task_valid, 4), + _p(cutlass.Int32, expert_base, 4), + _p(cutlass.Float32, alpha, 4), + _p(cutlass.Float32, input_gs, 4), + _p(cutlass.Uint8, lut, 4), + _p(cutlass.Float16, rot, 4), + _p(cutlass.Int32, task_head, 4), + _p(cutlass.Int32, p2_task_head, 4), + current_cuda_stream(), + ) + + fn_static = _compile(False) + fn_dyn = _compile(True) + out_static = torch.zeros((inter_total_words,), dtype=torch.uint32, device=device) + out_dyn = torch.zeros((inter_total_words,), dtype=torch.uint32, device=device) + + def _run(fn, out_buf, eb_buf): + fn( + _p(cutlass.Uint32, packed_a), + _p(cutlass.Uint8, scale_storage), + _p(cutlass.Uint32, w13_rp), + _p(cutlass.Uint32, w13_sfb_rp), + _p(cutlass.Uint32, out_buf), + _p(cutlass.Int32, token_map, 4), + _p(cutlass.Float32, token_weights, 4), + _p(cutlass.Int32, task_expert, 4), + _p(cutlass.Int32, task_valid, 4), + _p(cutlass.Int32, eb_buf, 4), + _p(cutlass.Float32, alpha, 4), + _p(cutlass.Float32, input_gs, 4), + _p(cutlass.Uint8, lut, 4), + _p(cutlass.Float16, rot, 4), + _p(cutlass.Int32, task_head, 4), + _p(cutlass.Int32, p2_task_head, 4), + current_cuda_stream(), + ) + torch.cuda.synchronize() + + _run(fn_static, out_static, expert_base) + task_head.zero_() + p2_task_head.fill_(12345) + _run(fn_dyn, out_dyn, expert_base) + assert p2_task_head.item() == 0 + assert out_static.ne(0).any() + assert torch.equal(out_static, out_dyn) + + # Empty launch (task_tail == 0): p2_task_head must still reset and task_head stays 0. + empty_base = torch.zeros((E + 1,), dtype=torch.int32, device=device) + out_empty = torch.zeros((inter_total_words,), dtype=torch.uint32, device=device) + task_head.zero_() + p2_task_head.fill_(9876) + _run(fn_dyn, out_empty, empty_base) + assert p2_task_head.item() == 0 + assert task_head.item() == 0 + assert out_empty.eq(0).all() + + +def test_w4a8_m128_phase2_worksteal_counter_reset_and_empty_direct(): + """Direct SM120 Phase-2 work-stealing across all 6 buckets, p1_task_head reset, and task_tail==0.""" + import cutlass + import cutlass.cute as cute + from cutlass.cute.runtime import make_ptr + + from b12x._lib.utils.device import current_cuda_stream + from b12x.moe._shared.kernels.w4a8_phase2 import W4A8MaterializedPhase2Kernel + + device = require_b12x() + E = 6 + counts = (16, 32, 48, 64, 96, 128) + M, N, K = E * 128, 512, 512 + inter_tiles = N // 128 + packed_out_tiles = K // 256 + words_per_row = inter_tiles * 32 + gen = torch.Generator(device="cpu").manual_seed(720) + inter_vals = torch.randint( + 0x30, 0x48, (M * words_per_row * 4,), generator=gen, dtype=torch.uint8 + ).view(torch.uint32) + inter_scales = torch.full((inter_tiles * M,), 0x7F7F7F7F, dtype=torch.int32).view( + torch.uint32 + ) + inter = torch.cat([inter_vals, inter_scales]).to(device) + down_rp = torch.randint( + 0, 1 << 30, (E * K * (N // 32) * 4,), generator=gen, dtype=torch.int32 + ).to(device=device, dtype=torch.uint32) + down_sfb = torch.full( + (E * (K // 128) * inter_tiles * 128,), + 0x7F7F7F7F, + dtype=torch.int32, + device=device, + ).to(torch.uint32) + tok_map = torch.arange(M, dtype=torch.int32, device=device) + tok_w = torch.full((M,), 0.5, dtype=torch.float32, device=device) + task_expert = torch.repeat_interleave( + torch.arange(E, dtype=torch.int32, device=device), inter_tiles + ) + task_valid = torch.repeat_interleave( + torch.tensor(counts, dtype=torch.int32, device=device), inter_tiles + ) + expert_base = torch.arange(E + 1, dtype=torch.int32, device=device) + alpha = torch.ones((E,), dtype=torch.float32, device=device) + gs = torch.ones((E,), dtype=torch.float32, device=device) + lut = torch.zeros((1,), dtype=torch.uint8, device=device) + p2_head = torch.zeros((1,), dtype=torch.int32, device=device) + p1_head = torch.zeros((1,), dtype=torch.int32, device=device) + + p2 = W4A8MaterializedPhase2Kernel( + source_tile_m=128, + n64_repacked=True, + deterministic_output=True, + ) + + def _p(dtype, t, align=16): + return make_ptr( + dtype, t.data_ptr(), cute.AddressSpace.gmem, assumed_align=align + ) + + def _compile(use_dyn: bool): + @cute.jit + def _wrap( + inter_p, + drp_p, + dsfb_p, + sc_p, + tm_p, + tw_p, + te_p, + tv_p, + eb_p, + al_p, + gs_p, + lut_p, + p2h_p, + p1h_p, + stream, + ): + inter_t = cute.make_tensor( + inter_p, cute.make_layout((inter.numel(),), stride=(1,)) + ) + drp_t = cute.make_tensor( + drp_p, cute.make_layout((down_rp.numel(),), stride=(1,)) + ) + dsfb_t = cute.make_tensor( + dsfb_p, cute.make_layout((down_sfb.numel(),), stride=(1,)) + ) + sc_t = cute.make_tensor(sc_p, cute.make_layout((M, K), stride=(K, 1))) + tm_t = cute.make_tensor(tm_p, cute.make_layout((M,), stride=(1,))) + tw_t = cute.make_tensor(tw_p, cute.make_layout((M,), stride=(1,))) + te_t = cute.make_tensor( + te_p, cute.make_layout((task_expert.numel(),), stride=(1,)) + ) + tv_t = cute.make_tensor( + tv_p, cute.make_layout((task_valid.numel(),), stride=(1,)) + ) + eb_t = cute.make_tensor(eb_p, cute.make_layout((E + 1,), stride=(1,))) + al_t = cute.make_tensor(al_p, cute.make_layout((E,), stride=(1,))) + gs_t = cute.make_tensor(gs_p, cute.make_layout((E,), stride=(1,))) + lut_t = cute.make_tensor(lut_p, cute.make_layout((1,), stride=(1,))) + p2h_t = cute.make_tensor(p2h_p, cute.make_layout((1,), stride=(1,))) + p1h_t = cute.make_tensor(p1h_p, cute.make_layout((1,), stride=(1,))) + p2( + inter_t, + drp_t, + dsfb_t, + sc_t, + tm_t, + tw_t, + te_t, + tv_t, + eb_t, + al_t, + gs_t, + lut_t, + cutlass.Int32(inter_tiles), + cutlass.Int32(packed_out_tiles), + cutlass.Int32(4), + cutlass.Int32(0), + stream, + task_head=p2h_t if use_dyn else None, + p1_task_head=p1h_t if use_dyn else None, + ) + + out_tmp = torch.zeros((M, K), dtype=torch.bfloat16, device=device) + return cute.compile( + _wrap, + _p(cutlass.Uint32, inter), + _p(cutlass.Uint32, down_rp), + _p(cutlass.Uint32, down_sfb), + _p(cutlass.BFloat16, out_tmp, 4), + _p(cutlass.Int32, tok_map, 4), + _p(cutlass.Float32, tok_w, 4), + _p(cutlass.Int32, task_expert, 4), + _p(cutlass.Int32, task_valid, 4), + _p(cutlass.Int32, expert_base, 4), + _p(cutlass.Float32, alpha, 4), + _p(cutlass.Float32, gs, 4), + _p(cutlass.Uint8, lut, 4), + _p(cutlass.Int32, p2_head, 4), + _p(cutlass.Int32, p1_head, 4), + current_cuda_stream(), + ) + + fn_static = _compile(False) + fn_dyn = _compile(True) + out_static = torch.zeros((M, K), dtype=torch.bfloat16, device=device) + out_dyn = torch.zeros((M, K), dtype=torch.bfloat16, device=device) + + def _run(fn, out_buf, eb_buf): + out_buf.zero_() + fn( + _p(cutlass.Uint32, inter), + _p(cutlass.Uint32, down_rp), + _p(cutlass.Uint32, down_sfb), + _p(cutlass.BFloat16, out_buf, 4), + _p(cutlass.Int32, tok_map, 4), + _p(cutlass.Float32, tok_w, 4), + _p(cutlass.Int32, task_expert, 4), + _p(cutlass.Int32, task_valid, 4), + _p(cutlass.Int32, eb_buf, 4), + _p(cutlass.Float32, alpha, 4), + _p(cutlass.Float32, gs, 4), + _p(cutlass.Uint8, lut, 4), + _p(cutlass.Int32, p2_head, 4), + _p(cutlass.Int32, p1_head, 4), + current_cuda_stream(), + ) + torch.cuda.synchronize() + + _run(fn_static, out_static, expert_base) + assert torch.isfinite(out_static).all() + for tile_idx, live_rows in enumerate(counts): + row_start = tile_idx * 128 + assert out_static[row_start : row_start + live_rows].ne(0).any() + if live_rows < 128: + assert out_static[row_start + live_rows : row_start + 128].eq(0).all() + + # Multi-replay work stealing with poisoned p1_task_head reset each launch. + for _ in range(3): + p2_head.zero_() + p1_head.fill_(54321) + _run(fn_dyn, out_dyn, expert_base) + assert p1_head.item() == 0 + assert torch.equal(out_static.view(torch.uint16), out_dyn.view(torch.uint16)) + + # Empty launch (task_tail == 0): p1_task_head resets to 0 and p2_head stays 0. + empty_base = torch.zeros((E + 1,), dtype=torch.int32, device=device) + p2_head.zero_() + p1_head.fill_(8765) + _run(fn_dyn, out_dyn, empty_base) + assert p1_head.item() == 0 + assert p2_head.item() == 0 + assert out_dyn.eq(0).all() + + +@pytest.mark.parametrize( + "input_format,route_planner,deterministic,tile_m,m,top_k,expert_count,counts,inactive_routes", + [ + pytest.param( + "mxfp8", + "triton", + False, + 128, + 384, + 1, + 6, + (16, 32, 48, 64, 96, 110), + 12, + id="mxfp8-triton-m128", + ), + pytest.param( + "bf16", + "triton", + False, + 16, + 64, + 1, + 4, + (1, 15, 16, 17), + 6, + id="bf16-triton-m16", + ), + pytest.param( + "bf16", + "internal", + True, + 128, + 160, + 2, + 4, + (16, 48, 65, 96), + 12, + id="bf16-internal-m128", + ), + ], +) +def test_w4a8_m128_poisoned_scratch_replay( + input_format: str, + route_planner: str, + deterministic: bool, + tile_m: int, + m: int, + top_k: int, + expert_count: int, + counts: tuple[int, ...], + inactive_routes: int, +): + """Supported route-planner paths reset poisoned scratch counters across replays.""" + device = require_b12x() + k, n = 512, 576 + experts, *_ = _build_experts(expert_count, k, n, device, seed=730) + gen = torch.Generator(device=device).manual_seed(731) + x = torch.randn((m, k), generator=gen, dtype=torch.bfloat16, device=device) * 0.25 + prequant = input_format == "mxfp8" + a_vals, a_scales = _quantize_mxfp8(x) if prequant else (None, None) + + def _sample_weights(route_ids: torch.Tensor) -> torch.Tensor: + if top_k == 1: + raw = torch.rand((m, 1), generator=gen, device=device) * 0.8 + 0.1 + else: + raw = torch.softmax( + torch.randn((m, top_k), generator=gen, device=device), dim=-1 + ) + return torch.where(route_ids >= 0, raw, torch.zeros_like(raw)) + + ids = _make_skewed_routes( + m, + top_k, + expert_count, + counts=counts, + inactive_routes=inactive_routes, + seed=732, + device=device, + ) + weights = _sample_weights(ids) + out = torch.empty((m, k), dtype=torch.bfloat16, device=device) + + plan = fused_moe.plan_execution( + experts=experts, + capacity=fused_moe.ExecutionCapacity( + max_tokens=m, top_k=top_k, input_format=input_format + ), + routing=fused_moe.RoutingSpec(deterministic_output=deterministic), + override=MoeDecodeConfig( + backend="dynamic", + route_planner=route_planner, + max_active_clusters=None, + dynamic_tile_m=tile_m, + dynamic_route_mode="grouped", + ), + ) + session = PreparationSession(compile_workers=0, autotune=False) + box = {} + + def _prep(state): + scratch = [ + torch.full((spec.nbytes,), 0x55, dtype=spec.dtype, device=device) + for spec in state.scratch.scratch_specs() + ] + bind_kwargs = dict(a=a_vals, a_scales=a_scales) if prequant else dict(a=x) + binding = state.bind( + **bind_kwargs, + topk_ids=ids, + topk_weights=weights, + output=out, + scratch=scratch, + input_scales_static=True, + ) + box["scratch"] = scratch + box["run"] = lambda: state.run(binding) + return PreparedCall(run=box["run"]) + + session.prepare( + ( + plan.request( + name=f"{input_format}_{route_planner}_m{tile_m}", prepare_call=_prep + ), + ) + ) + try: + for step in range(3): + for buf in box["scratch"]: + buf.fill_(0x55) + out.fill_(float("nan")) + if step == 1: + ids.fill_(-1) + weights.zero_() + else: + ids.copy_( + _make_skewed_routes( + m, + top_k, + expert_count, + counts=counts, + inactive_routes=inactive_routes, + seed=732 + step, + device=device, + ) + ) + weights.copy_(_sample_weights(ids)) + ref = _run_moe( + experts, + x_bf16=None if prequant else x, + a_vals=a_vals if prequant else None, + a_scales=a_scales if prequant else None, + topk_ids=ids, + topk_weights=weights, + tile_m=64, + route_planner="internal", + deterministic=True, + ) + box["run"]() + torch.cuda.synchronize() + torch.testing.assert_close(out, ref, rtol=0, atol=0) + finally: + session.close()