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] 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, + )