From e16c7e547ddb39b8f035f6be06e481e488c92b5b Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Fri, 30 Oct 2026 05:49:30 +0800 Subject: [PATCH 01/14] feat: native BF16 GEMM for dense, batch and grouped entry points Add a native BF16 MMA path on the self-developed SM100 mainloop: no scale factors, a shape-aware tile ladder, tail-only stream-K and M-fast tile traversal. - gemm_tile / kernel_traits: KIsBF16 tile vocabulary, MMA atom width decoupled from the cluster shape (KAtomCtas), epilogue warp-group override, predicated N-tail store and right-sized TMEM allocation. - bf16_cfgs.h: 35-tile dense catalog plus batch / contiguous / masked catalogs with their dispatch selectors and per-tier entry guards. - mainloop / epilogue: BF16 has no SF operands (default TMA atoms, zero-sized SFA/SFB smem); fp32 partial deposit plus a stream-K reduce kernel for split tails. - tile_scheduler: M-fast traversal and tail-only stream-K decomposition. - dense_gemm / batch_gemm / group_{masked,contiguous}_gemm: mode="bf16". - python: sfa / sfb are Optional and become empty tensors for bf16. - benchmark: bf16 dense / batch / grouped configs, a batch_gemm scenario, CI configs and baselines; golden / deepgemm / flashinfer bf16 backends. - tests: BF16 dense and batch / grouped accuracy tests. Co-Authored-By: Claude Code --- README.md | 10 +- README_CN.md | 10 +- benchmark/ci_configs/gemm/batch_bf16.yaml | 23 + benchmark/ci_configs/gemm/dense_bf16.yaml | 24 + benchmark/configs/gemm/batch_bf16.yaml | 36 + benchmark/configs/gemm/dense_bf16.yaml | 30 + .../configs/gemm/group_contiguous_bf16.yaml | 24 + benchmark/configs/gemm/group_masked_bf16.yaml | 24 + benchmark/core/report.py | 7 +- benchmark/docs/config_schema.md | 17 +- benchmark/kernel/gemm/backends/deepgemm.py | 46 + benchmark/kernel/gemm/backends/flashinfer.py | 36 + benchmark/kernel/gemm/backends/golden.py | 32 +- benchmark/kernel/gemm/backends/halops.py | 18 +- benchmark/kernel/gemm/scenarios/__init__.py | 2 + benchmark/kernel/gemm/scenarios/batch_gemm.py | 345 ++++++ benchmark/kernel/gemm/scenarios/dense_gemm.py | 46 +- .../kernel/gemm/scenarios/grouped_gemm.py | 36 +- ci/baselines/gemm/batch_bf16.json | 133 +++ ci/baselines/gemm/dense_bf16.json | 147 +++ csrc/kernel/gemm/batch_gemm.cu | 49 +- csrc/kernel/gemm/bf16_cfgs.h | 1015 +++++++++++++++++ csrc/kernel/gemm/dense_gemm.cu | 212 +++- csrc/kernel/gemm/epilogue.cuh | 561 ++++++++- csrc/kernel/gemm/gemm_kernel.cuh | 196 +++- csrc/kernel/gemm/gemm_tile.cuh | 244 +++- csrc/kernel/gemm/gemm_utils.h | 24 + csrc/kernel/gemm/group_contiguous_gemm.cu | 48 +- csrc/kernel/gemm/group_masked_gemm.cu | 49 +- csrc/kernel/gemm/kernel_traits.cuh | 417 +++++-- csrc/kernel/gemm/mainloop_fwd.cuh | 349 +++--- csrc/kernel/gemm/stream_k_reduce.cuh | 108 ++ csrc/kernel/gemm/tile_scheduler.cuh | 382 ++++++- csrc/kernel/gemm/utils.cuh | 9 + halops/gemm/batch_gemm.py | 13 +- halops/gemm/dense_gemm.py | 14 +- halops/gemm/group_contiguous_gemm.py | 14 +- halops/gemm/group_masked_gemm.py | 13 +- tests/test_gemm_bf16.py | 139 +++ tests/test_gemm_bf16_grouped.py | 172 +++ 40 files changed, 4715 insertions(+), 359 deletions(-) create mode 100644 benchmark/ci_configs/gemm/batch_bf16.yaml create mode 100644 benchmark/ci_configs/gemm/dense_bf16.yaml create mode 100644 benchmark/configs/gemm/batch_bf16.yaml create mode 100644 benchmark/configs/gemm/dense_bf16.yaml create mode 100644 benchmark/configs/gemm/group_contiguous_bf16.yaml create mode 100644 benchmark/configs/gemm/group_masked_bf16.yaml create mode 100644 benchmark/kernel/gemm/scenarios/batch_gemm.py create mode 100644 ci/baselines/gemm/batch_bf16.json create mode 100644 ci/baselines/gemm/dense_bf16.json create mode 100644 csrc/kernel/gemm/bf16_cfgs.h create mode 100644 csrc/kernel/gemm/stream_k_reduce.cuh create mode 100644 tests/test_gemm_bf16.py create mode 100644 tests/test_gemm_bf16_grouped.py diff --git a/README.md b/README.md index f7be872..e10a7d3 100644 --- a/README.md +++ b/README.md @@ -100,9 +100,17 @@ dense_gemm(a_fp8, b_fp8, scale_a, scale_b, output, mode="w8a8-mxfp8") print(output.shape, output.dtype) ``` +Native BF16 needs no quantization; pass `None` for the scale factors: + +```python +output = torch.empty((M, N), device="cuda", dtype=torch.bfloat16) +dense_gemm(a, b, None, None, output, mode="bf16") +print(output.shape, output.dtype) +``` + ## Roadmap -- **Complete GEMM coverage**: add W4A8, BF16 and other GEMM types to build a full quantization-type support matrix, so users can pick the trade-off between inference speed and accuracy they need. +- **Complete GEMM coverage**: add W4A8 and other GEMM types to build a full quantization-type support matrix, so users can pick the trade-off between inference speed and accuracy they need. - **Higher-performance MegaKernels**: cover more compute-communication fusion scenarios and further overlap compute with memory traffic. ## Contributing diff --git a/README_CN.md b/README_CN.md index 52706ed..ec05f91 100644 --- a/README_CN.md +++ b/README_CN.md @@ -100,9 +100,17 @@ dense_gemm(a_fp8, b_fp8, scale_a, scale_b, output, mode="w8a8-mxfp8") print(output.shape, output.dtype) ``` +原生 BF16 不需要量化,scale factor 传 `None` 即可: + +```python +output = torch.empty((M, N), device="cuda", dtype=torch.bfloat16) +dense_gemm(a, b, None, None, output, mode="bf16") +print(output.shape, output.dtype) +``` + ## 路线图 -- **全面的 GEMM 支持矩阵**:覆盖 W4A8、BF16 等类型的 GEMM,打造全量化类型的 GEMM 支持矩阵,满足不同推理性能与效果需求下的选择。 +- **全面的 GEMM 支持矩阵**:覆盖 W4A8 等类型的 GEMM,打造全量化类型的 GEMM 支持矩阵,满足不同推理性能与效果需求下的选择。 - **更高性能的巨内核方案**:覆盖更多场景的通算融合,以及计算与访存 overlap 的优化方案。 ## 如何贡献 diff --git a/benchmark/ci_configs/gemm/batch_bf16.yaml b/benchmark/ci_configs/gemm/batch_bf16.yaml new file mode 100644 index 0000000..172c94f --- /dev/null +++ b/benchmark/ci_configs/gemm/batch_bf16.yaml @@ -0,0 +1,23 @@ +scenario: batch_gemm +mode: bf16 + +# CI regression subset for native BF16 batch GEMM, mirroring the shapes in +# benchmark/configs/gemm/batch_bf16.yaml. halops-only + refcheck off, per the +# ci_configs convention (baseline comparison is halops-vs-baseline). +# [B, M, N, K]. +shapes: + - [8, 8192, 1024, 4096] + - [8192, 64, 128, 4096] + - [8192, 64, 512, 576] + - [8192, 64, 512, 64] + - [8192, 64, 256, 64] + - [8, 1024, 4096, 4096] + - [8, 128, 4096, 4096] + - [4, 256, 7168, 4096] + - [1, 8192, 4096, 4096] +sm_count: -1 + +backends: [halops] +cold_l2_cache: true +refcheck: false +refcheck_reference: golden diff --git a/benchmark/ci_configs/gemm/dense_bf16.yaml b/benchmark/ci_configs/gemm/dense_bf16.yaml new file mode 100644 index 0000000..193da81 --- /dev/null +++ b/benchmark/ci_configs/gemm/dense_bf16.yaml @@ -0,0 +1,24 @@ +scenario: dense_gemm +mode: bf16 + +# CI regression subset for native BF16 dense GEMM, mirroring the routine +# 10-shape preset in benchmark/configs/gemm/dense_bf16.yaml. +# halops-only + refcheck off, per the ci_configs convention (baseline +# comparison is halops-vs-baseline). +shapes: + - [64, 4096, 4096] + - [64, 32768, 1024] + - [128, 4096, 4096] + - [128, 128, 4096] + - [256, 4096, 4096] + - [1024, 4096, 4096] + - [1024, 1600, 4096] + - [1024, 32768, 1024] + - [4096, 4096, 4096] + - [8192, 32768, 1024] +sm_count: -1 + +backends: [halops] +cold_l2_cache: true +refcheck: false +refcheck_reference: golden diff --git a/benchmark/configs/gemm/batch_bf16.yaml b/benchmark/configs/gemm/batch_bf16.yaml new file mode 100644 index 0000000..903c2c5 --- /dev/null +++ b/benchmark/configs/gemm/batch_bf16.yaml @@ -0,0 +1,36 @@ +# Batch GEMM BF16 baseline: representative model shapes vs cuBLAS (torch.bmm). +# +# The [B, M, N, K] convention: batch item b computes input[b] @ weight[b]^T, +# i.e. [M, K] @ [K, N] -> [M, N]. batch_gemm dispatches on total_m = B*M. +# +# Backends: +# halops -- our native BF16 batch GEMM (3-tier dispatch: 256x256 pair / +# 128x256 / SwapAB 128x64) +# fi -- flashinfer.bmm_bf16, cuDNN backend (the default the dense +# bf16 path also uses) +# fi_cutlass -- flashinfer.bmm_bf16, CUTLASS backend, so flashinfer's own +# kernels and its cuDNN fallback can be told apart +# bmm -- torch.bmm (cuBLAS) +scenario: batch_gemm +mode: bf16 + +shapes: + # batched output projection (8 experts) + - [8, 8192, 1024, 4096] + # per-token bmms (batch=8192, M=64) + - [8192, 64, 128, 4096] + - [8192, 64, 512, 576] + - [8192, 64, 512, 64] + - [8192, 64, 256, 64] + # smaller batch variants to cover the dispatch tiers + - [8, 1024, 4096, 4096] + - [8, 128, 4096, 4096] + - [4, 256, 7168, 4096] + - [1, 8192, 4096, 4096] + +sm_count: -1 + +backends: [halops, fi, fi_cutlass, bmm] +cold_l2_cache: true +refcheck: true +refcheck_reference: golden diff --git a/benchmark/configs/gemm/dense_bf16.yaml b/benchmark/configs/gemm/dense_bf16.yaml new file mode 100644 index 0000000..fa8d7de --- /dev/null +++ b/benchmark/configs/gemm/dense_bf16.yaml @@ -0,0 +1,30 @@ +# configs/gemm/dense_bf16.yaml +# Default quick preset: 10 shapes, for routine runs. Picks one or two +# representatives per M-based dispatch tier in DenseGemm (dense_gemm.cu), plus +# the odd-N shapes and the biggest absolute-loss shape. +# +# M=64 x2 thin-M non-swap rung (incl. widest N=32768) +# M=128 x2 thin-M / 96-wide rung (incl. narrow N=128) +# M=256 x1 mid-M ladder entry +# M=1024 x3 mid-M valley + N=1600 + widest N +# M=4096 x1 large-M square +# M=8192 x1 large-M, N=32768 family +scenario: dense_gemm +mode: bf16 +shapes: + - [64, 4096, 4096] # thin-M + - [64, 32768, 1024] # thin-M widest N + - [128, 4096, 4096] # thin-M / 96-wide rung + - [128, 128, 4096] # narrow N + - [256, 4096, 4096] # mid-M ladder entry + - [1024, 4096, 4096] # mid-M valley + - [1024, 1600, 4096] # N=1600 (predicated N-tail) + - [1024, 32768, 1024] # mid-M widest N + - [4096, 4096, 4096] # large-M square + - [8192, 32768, 1024] # large-M, biggest absolute-loss shape +sm_count: -1 + +backends: [halops, fi, deepgemm] +cold_l2_cache: true +refcheck: true +refcheck_reference: golden diff --git a/benchmark/configs/gemm/group_contiguous_bf16.yaml b/benchmark/configs/gemm/group_contiguous_bf16.yaml new file mode 100644 index 0000000..b2ba1fd --- /dev/null +++ b/benchmark/configs/gemm/group_contiguous_bf16.yaml @@ -0,0 +1,24 @@ +# configs/gemm/group_contiguous_bf16.yaml +# Grouped contiguous native BF16 GEMM (mode="bf16") on the self-developed +# CollectiveMainloop. No quantization / scale factors; the golden +# torch.matmul (bf16, no dequant) is the refcheck reference. +scenario: group_contiguous +mode: bf16 + +# [num_experts, max_m, N, K] shapes (total m = num_experts * max_m, aligned to +# tile_m boundaries). N a multiple of 256, K a multiple of 64. +shapes: + - [4, 128, 256, 512] + - [4, 256, 1024, 1024] + - [8, 512, 7168, 3584] + - [10, 4096, 7168, 3584] + - [4, 128, 4096, 4096] + - [8, 512, 4096, 4096] + - [8, 1024, 4096, 4096] + - [10, 4096, 4096, 4096] +sm_count: -1 + +backends: [halops, fi, deepgemm] +cold_l2_cache: true +refcheck: true +refcheck_reference: golden diff --git a/benchmark/configs/gemm/group_masked_bf16.yaml b/benchmark/configs/gemm/group_masked_bf16.yaml new file mode 100644 index 0000000..577fef6 --- /dev/null +++ b/benchmark/configs/gemm/group_masked_bf16.yaml @@ -0,0 +1,24 @@ +# configs/gemm/group_masked_bf16.yaml +# Grouped masked native BF16 GEMM (mode="bf16") on the self-developed +# CollectiveMainloop. No quantization / scale factors; the golden +# torch.matmul (bf16, no dequant) is the refcheck reference. +scenario: group_masked +mode: bf16 + +# [num_experts, max_m, N, K] shapes. max_m must be a multiple of the tile_m +# (128), N a multiple of 256, K a multiple of 64. +shapes: + - [4, 128, 256, 512] + - [4, 256, 1024, 1024] + - [8, 512, 7168, 3584] + - [10, 4096, 7168, 3584] + - [4, 128, 4096, 4096] + - [8, 512, 4096, 4096] + - [8, 1024, 4096, 4096] + - [10, 4096, 4096, 4096] +sm_count: -1 + +backends: [halops, fi, deepgemm] +cold_l2_cache: true +refcheck: true +refcheck_reference: golden diff --git a/benchmark/core/report.py b/benchmark/core/report.py index bcaea97..42348e3 100644 --- a/benchmark/core/report.py +++ b/benchmark/core/report.py @@ -33,7 +33,12 @@ def _is_gemm_scenario(scenario): - _GEMM_SCENARIOS = ("dense_gemm", "group_masked", "group_contiguous") + _GEMM_SCENARIOS = ( + "dense_gemm", + "group_masked", + "group_contiguous", + "batch_gemm", + ) return True if scenario in _GEMM_SCENARIOS else False diff --git a/benchmark/docs/config_schema.md b/benchmark/docs/config_schema.md index 81d94b5..d0e1d5a 100644 --- a/benchmark/docs/config_schema.md +++ b/benchmark/docs/config_schema.md @@ -103,9 +103,20 @@ 普通参数: -- `mode`(默认 `w8a8-mxfp8`):支持 `w8a8-mxfp8` 和 `w4a4-nvfp4`(kernel 与 `group_wise_quant` 也支持 `w4a4-mxfp4`,但 benchmark 暂未生成对应的量化输入)。 +- `mode`(默认 `w8a8-mxfp8`):支持 `w8a8-mxfp8`、`w4a4-nvfp4` 与原生 BF16 `bf16`(kernel 与 `group_wise_quant` 也支持 `w4a4-mxfp4`,但 benchmark 暂未生成对应的量化输入)。`bf16` 模式下不生成量化输入,`sfa`/`sfb` 为 `None`,且要求 `K` 为 `64` 的倍数。 - `sm_count`(默认 `-1`):`-1` 表示不限制 SM 数量。 +### `batch_gemm` + +遍历维度参数: + +- `shapes`(必选):`[B, M, N, K]` 列表,每项生成一个 case;第 `b` 个 batch 计算 `input[b] @ weight[b]^T`。 + +普通参数: + +- `mode`(默认 `bf16`):当前仅支持原生 BF16 `bf16`,要求 `K` 为 `64` 的倍数。 +- `sm_count`(默认 `-1`)。 + ### `group_masked` 和 `group_contiguous` 遍历维度参数: @@ -114,7 +125,7 @@ 普通参数: -- `mode`(默认 `w8a8-mxfp8`):支持 `w8a8-mxfp8` 和 `w4a4-nvfp4`(grouped kernel 与 `group_wise_quant` 也支持 `w4a4-mxfp4`,但 benchmark 暂未生成对应的量化输入)。 +- `mode`(默认 `w8a8-mxfp8`):支持 `w8a8-mxfp8`、`w4a4-nvfp4` 与原生 BF16 `bf16`(grouped kernel 与 `group_wise_quant` 也支持 `w4a4-mxfp4`,但 benchmark 暂未生成对应的量化输入)。`bf16` 模式要求 `K` 为 `64` 的倍数。 - `sm_count`(默认 `-1`)。 所有现有 GEMM 场景均要求 `K` 为 `32` 的倍数。 @@ -135,3 +146,5 @@ - `backends`:`halops`。 固定形状为 `hidden_size=4096`、`intermediate_size=512`、`latent_size=2048`、`num_experts=512`,配置其他形状会报错。 + +原生 BF16 模式要求 `K` 为 `64` 的倍数。 diff --git a/benchmark/kernel/gemm/backends/deepgemm.py b/benchmark/kernel/gemm/backends/deepgemm.py index 7f78e8b..0061370 100644 --- a/benchmark/kernel/gemm/backends/deepgemm.py +++ b/benchmark/kernel/gemm/backends/deepgemm.py @@ -68,6 +68,16 @@ def make_dense_inputs(x_bf16: torch.Tensor, w_bf16: torch.Tensor, mode: str) -> n = w_bf16.shape[0] out = torch.empty(m, n, dtype=torch.bfloat16, device=x_bf16.device) + if mode == "bf16": + # Native BF16: no quantization / scale factors. bf16_gemm_nt computes + # a @ b.T, so pass w_bf16 [N, K] directly as b. + return { + "a": x_bf16, + "b": w_bf16, + "out": out, + "mode": mode, + } + cast = ( dg.per_token_cast_to_fp4 if mode.startswith("w4a4") @@ -112,6 +122,19 @@ def make_grouped_masked_inputs( a_bf16 = x_bf16.reshape(num_groups, max_m, k) masked_m = masked_m.to(device=dev, dtype=torch.int32) + if mode == "bf16": + # Native BF16: 3D masked layout, no quantization / scale factors. + # m_grouped_bf16_gemm_nt_masked computes a @ b.T per group. + out = torch.empty(num_groups, max_m, n, dtype=torch.bfloat16, device=dev) + return { + "a": a_bf16, + "b": w_bf16, + "out": out, + "masked_m": masked_m, + "max_m": max_m, + "mode": mode, + } + if mode.startswith("w4a4"): # A: FP4 per-token (gran_k=32), pre-pack SF to UE8M0 INT a_fp4 = torch.empty(num_groups, max_m, k // 2, dtype=torch.int8, device=dev) @@ -194,6 +217,19 @@ def make_grouped_contiguous_inputs( dev = x_bf16.device m_indices = m_indices.to(device=dev, dtype=torch.int32) + if mode == "bf16": + # Native BF16: 2D contiguous layout, no quantization / scale factors. + # m_grouped_bf16_gemm_nt_contiguous computes a @ b.T with per-row expert + # routing given by m_indices. + out = torch.empty(m, n, dtype=torch.bfloat16, device=dev) + return { + "a": x_bf16, + "b": w_bf16, + "out": out, + "m_indices": m_indices, + "mode": mode, + } + if mode.startswith("w4a4"): a_fp4, a_sf = dg.per_token_cast_to_fp4(x_bf16, use_ue8m0=True, gran_k=32) a_sf_packed = dg.get_mn_major_tma_aligned_packed_ue8m0_tensor(a_sf) @@ -247,6 +283,8 @@ def run_dense_gemm(inp: dict): dg.fp8_fp4_gemm_nt( inp["a"], inp["b"], inp["out"], recipe_a=(1, 32), recipe_b=(1, 32) ) + elif inp.get("mode") == "bf16": + dg.bf16_gemm_nt(inp["a"], inp["b"], inp["out"]) else: dg.fp8_gemm_nt( inp["a"], inp["b"], inp["out"], recipe_a=(1, 32), recipe_b=(1, 32) @@ -269,6 +307,10 @@ def run_group_masked_gemm(inp: dict): recipe_a=(1, 32), recipe_b=(1, 32), ) + elif inp.get("mode") == "bf16": + dg.m_grouped_bf16_gemm_nt_masked( + inp["a"], inp["b"], inp["out"], inp["masked_m"], inp["max_m"] + ) else: dg.m_grouped_fp8_gemm_nt_masked( inp["a"], inp["b"], inp["out"], inp["masked_m"], inp["max_m"] @@ -290,6 +332,10 @@ def run_group_contiguous_gemm(inp: dict): recipe_a=(1, 32), recipe_b=(1, 32), ) + elif inp.get("mode") == "bf16": + dg.m_grouped_bf16_gemm_nt_contiguous( + inp["a"], inp["b"], inp["out"], inp["m_indices"] + ) else: dg.m_grouped_fp8_gemm_nt_contiguous( inp["a"], inp["b"], inp["out"], inp["m_indices"] diff --git a/benchmark/kernel/gemm/backends/flashinfer.py b/benchmark/kernel/gemm/backends/flashinfer.py index ecb0844..29ba25c 100644 --- a/benchmark/kernel/gemm/backends/flashinfer.py +++ b/benchmark/kernel/gemm/backends/flashinfer.py @@ -47,6 +47,16 @@ def run_fi_dense_gemm(inp: dict): # scales (M_padded * K_padded,). mode = inp.get("mode", "w8a8-mxfp8") backend = _fi_backend(inp) + if mode == "bf16": + # flashinfer's CUTLASS bf16 kernel is not sm100-tuned (~18% roofline); + # its documented default backend "cudnn" is ~2x faster on large shapes. + # Keep it overridable via inp["backend"] for per-shape experiments. + return flashinfer.mm_bf16( + inp["x"], + inp["w"].T, + out=inp["out"], + backend=backend, + ) if mode == "w4a4-mxfp4": raise ValueError("flashinfer backend does not support mode 'w4a4-mxfp4' yet") if mode == "w4a4-nvfp4": @@ -75,6 +85,25 @@ def run_fi_dense_gemm(inp: dict): ) +def run_fi_batch_gemm(inp: dict): + """Run FlashInfer batched BF16 GEMM (bmm_bf16). + + This is FlashInfer's counterpart to torch.bmm for the per-token / per-expert + batched shapes. Like the dense bf16 path, its default "cudnn" backend is the + fast one; the CUTLASS one is offered separately so the gap between + FlashInfer's own kernels and its cuDNN fallback stays visible. + """ + _check() + import flashinfer + + return flashinfer.bmm_bf16( + inp["x"], + inp["bt"], + out=inp["out"], + backend=inp.get("backend", "cudnn"), + ) + + def run_fi_group_masked_gemm(inp: dict): """Run FlashInfer grouped masked GEMM (W8A8-MXFP8 via grouped_mm_mxfp8, W4A4 via grouped_mm_fp4).""" _check() @@ -83,6 +112,13 @@ def run_fi_group_masked_gemm(inp: dict): mode = inp.get("mode", "w8a8-mxfp8") m_indptr = inp["m_indptr"] + if mode == "bf16": + return flashinfer.grouped_mm_bf16( + inp["x"], + inp["w"], + m_indptr, + out=inp["out"], + ) if mode == "w4a4-mxfp4": raise ValueError("flashinfer backend does not support mode 'w4a4-mxfp4' yet") if mode == "w4a4-nvfp4": diff --git a/benchmark/kernel/gemm/backends/golden.py b/benchmark/kernel/gemm/backends/golden.py index c06bb68..80b5342 100644 --- a/benchmark/kernel/gemm/backends/golden.py +++ b/benchmark/kernel/gemm/backends/golden.py @@ -89,11 +89,17 @@ def run_dense_golden(inp: dict) -> torch.Tensor: the golden is a neutral baseline that excludes quantization noise and shares the kernels' compute and output dtype. - inp keys: x_bf16 [M, K], w_bf16 [N, K], mode ("w8a8-mxfp8" | "w4a4-nvfp4"). + inp keys: x_bf16 [M, K], w_bf16 [N, K], mode ("w8a8-mxfp8" | "w4a4-nvfp4" | + "bf16"). """ mode = inp.get("mode", "w8a8-mxfp8") - x = _dequant_to_bf16(inp["x_bf16"], mode) - w = _dequant_to_bf16(inp["w_bf16"], mode) + if mode == "bf16": + # Native BF16: the kernel consumes bf16 directly, no quantization noise. + x = inp["x_bf16"] + w = inp["w_bf16"] + else: + x = _dequant_to_bf16(inp["x_bf16"], mode) + w = _dequant_to_bf16(inp["w_bf16"], mode) return torch.matmul(x, w.t()) @@ -110,18 +116,26 @@ def run_grouped_golden(inp: dict) -> torch.Tensor: x_bf16 [M, K] unquantized activation source (bfloat16) w_bf16 [E, N, K] unquantized per-expert weight source (bfloat16) m_indptr [E+1] per-group row offsets (prefix sum) - mode str "w8a8-mxfp8" (fp8) or "w4a4-nvfp4" (fp4) + mode str "w8a8-mxfp8" (fp8), "w4a4-nvfp4" (fp4), or + "bf16" Returns: torch.Tensor [M, N] bfloat16 reference output. """ mode = inp.get("mode", "w8a8-mxfp8") - x = _dequant_to_bf16(inp["x_bf16"], mode) # [M, K] - w_src = inp["w_bf16"] # [E, N, K] + if mode == "bf16": + # Native BF16: the kernel consumes bf16 directly, no quantization noise. + x = inp["x_bf16"] # [M, K] + w_src = inp["w_bf16"] + w = w_src + else: + x = _dequant_to_bf16(inp["x_bf16"], mode) # [M, K] + w_src = inp["w_bf16"] # [E, N, K] + num_groups, n, k = w_src.shape + w = _dequant_to_bf16(w_src.reshape(num_groups * n, k), mode).reshape( + num_groups, n, k + ) num_groups, n, k = w_src.shape - w = _dequant_to_bf16(w_src.reshape(num_groups * n, k), mode).reshape( - num_groups, n, k - ) # Materialize offsets on CPU once to avoid per-group GPU->CPU syncs. offsets = inp["m_indptr"].tolist() out = torch.empty(x.shape[0], n, dtype=torch.bfloat16, device=x.device) diff --git a/benchmark/kernel/gemm/backends/halops.py b/benchmark/kernel/gemm/backends/halops.py index 30bc786..1503925 100644 --- a/benchmark/kernel/gemm/backends/halops.py +++ b/benchmark/kernel/gemm/backends/halops.py @@ -21,16 +21,20 @@ def run_dense_gemm(inp: dict): - """Run halops dense GEMM (W8A8-MXFP8/FP8 or W4A4/FP4). + """Run halops dense GEMM (W8A8-MXFP8/FP8, W4A4/FP4, or native BF16). inp keys: x [M, K] (w8a8-mxfp8) float8_e4m3fn / [M, K//2] (w4a4-nvfp4) uint8 packed + (bf16) bfloat16 w [N, K] (w8a8-mxfp8) float8_e4m3fn / [N, K//2] (w4a4-nvfp4) uint8 packed - sfa [M, K//32] (w8a8-mxfp8) / [M, K//16] (w4a4-nvfp4) uint8 (CUTLASS layout) - sfb [N, K//32] (w8a8-mxfp8) / [N, K//16] (w4a4-nvfp4) uint8 + (bf16) bfloat16 + sfa [M, K//32] (w8a8-mxfp8) / [M, K//16] (w4a4-nvfp4) uint8 (None for + bf16) + sfb [N, K//32] (w8a8-mxfp8) / [N, K//16] (w4a4-nvfp4) uint8 (None for + bf16) out [M, N] bfloat16, pre-allocated output - alpha [1] float32 (w4a4-nvfp4) / None (w8a8-mxfp8) - mode "w8a8-mxfp8" | "w4a4-nvfp4" + alpha [1] float32 (w4a4-nvfp4) / None (w8a8-mxfp8, bf16) + mode "w8a8-mxfp8" | "w4a4-nvfp4" | "bf16" sm_count int """ dense_gemm( @@ -48,7 +52,7 @@ def run_dense_gemm(inp: dict): def run_group_masked_gemm(inp: dict): - """Run halops grouped masked GEMM (W8A8-MXFP8/FP8 or W4A4/FP4). + """Run halops grouped masked GEMM (W8A8-MXFP8/FP8, W4A4/FP4, or BF16). inp keys: x [E*max_m, K] (w8a8-mxfp8) float8_e4m3fn / [E*max_m, K//2] (w4a4-nvfp4) uint8 @@ -79,7 +83,7 @@ def run_group_masked_gemm(inp: dict): def run_group_contiguous_gemm(inp: dict): - """Run halops grouped contiguous GEMM (W8A8-MXFP8/FP8 or W4A4/FP4). + """Run halops grouped contiguous GEMM (W8A8-MXFP8/FP8, W4A4/FP4, or BF16). inp keys: x [M, K] (w8a8-mxfp8) float8_e4m3fn / [M, K//2] (w4a4-nvfp4) uint8 diff --git a/benchmark/kernel/gemm/scenarios/__init__.py b/benchmark/kernel/gemm/scenarios/__init__.py index b9b141f..afc1bdb 100644 --- a/benchmark/kernel/gemm/scenarios/__init__.py +++ b/benchmark/kernel/gemm/scenarios/__init__.py @@ -14,6 +14,7 @@ # limitations under the License. """ +from kernel.gemm.scenarios.batch_gemm import run_scenario as run_batch_gemm from kernel.gemm.scenarios.dense_gemm import run_scenario as run_dense_gemm from kernel.gemm.scenarios.grouped_gemm import ( run_group_masked, @@ -22,6 +23,7 @@ SCENARIOS = { "dense_gemm": run_dense_gemm, + "batch_gemm": run_batch_gemm, "group_masked": run_group_masked, "group_contiguous": run_group_contiguous, } diff --git a/benchmark/kernel/gemm/scenarios/batch_gemm.py b/benchmark/kernel/gemm/scenarios/batch_gemm.py new file mode 100644 index 0000000..eda2257 --- /dev/null +++ b/benchmark/kernel/gemm/scenarios/batch_gemm.py @@ -0,0 +1,345 @@ +""" +# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +Batch GEMM benchmark scenario for BF16 on SM100. + +Mirrors dense_gemm.py's structure. Shapes are [B, M, N, K] where B is the +batch (expert) count, and each batch item computes output[b] = input[b] @ +weight[b]^T, i.e. [M, K] @ [K, N] -> [M, N]. + +The batch count B maps to GemmRowResult.num_experts so the existing output +infrastructure (header, table, CSV) renders it without modification. + +Backends: + halops -- our native BF16 batch GEMM (batch_gemm.cu, 3-tier dispatch) + fi -- flashinfer.bmm_bf16, cuDNN backend (same default as the dense + bf16 path) + fi_cutlass -- flashinfer.bmm_bf16, CUTLASS backend, so flashinfer's own + kernels and its cuDNN fallback can be told apart + bmm -- torch.bmm (cuBLAS batch GEMM), the reference the model + currently uses in production via aten::bmm + +deep_gemm has no batched BF16 entry point (dense/grouped only), so unlike the +dense scenario there is no deepgemm row here. +""" + +from __future__ import annotations +import os +from dataclasses import dataclass +from functools import partial + +import torch + +from core.timing import bench_gpu_time +from core.metrics import compute_gemm_metrics +from core.runner import run_bench_for_backend, run_refcheck_cross_backends +from core.output import ( + GemmRowResult, + print_scenario_header, + print_table_header, + print_table_row, + append_gemm_csv, +) + +from halops import batch_gemm +from kernel.gemm.backends.flashinfer import run_fi_batch_gemm + + +@dataclass +class BatchGemmInput: + """Batch GEMM inputs for BF16 mode.""" + + x: torch.Tensor # [B, M, K] bfloat16 + w: torch.Tensor # [B, N, K] bfloat16 + out: torch.Tensor # [B, M, N] bfloat16 (torch.bmm / flashinfer layout) + out_halops: torch.Tensor # [M, B * N] bfloat16 (HALOps batch_gemm layout) + b: int + m: int + n: int + k: int + sm_count: int + mode: str = "bf16" + + +def _build_inputs( + b: int, m: int, n: int, k: int, sm_count: int, mode: str = "bf16" +) -> BatchGemmInput: + """Build batch GEMM inputs on CUDA for BF16 mode.""" + dev = "cuda" + assert mode == "bf16", f"batch scenario supports bf16 only, got {mode}" + assert k % 64 == 0, f"k={k} must be divisible by 64 for bf16" + + x = torch.randn(b, m, k, dtype=torch.bfloat16, device=dev) + w = torch.randn(b, n, k, dtype=torch.bfloat16, device=dev) + out = torch.empty(b, m, n, dtype=torch.bfloat16, device=dev) + out_halops = torch.empty(m, b * n, dtype=torch.bfloat16, device=dev) + + return BatchGemmInput( + x=x, + w=w, + out=out, + out_halops=out_halops, + b=b, + m=m, + n=n, + k=k, + sm_count=sm_count, + mode=mode, + ) + + +def adapt_halops(inp: BatchGemmInput) -> dict: + """Adapt inputs for the HALOps backend.""" + return { + "x": inp.x, + "w": inp.w, + "out": inp.out_halops, + "sfa": None, + "sfb": None, + "bias": None, + "alpha": None, + "sm_count": inp.sm_count, + "mode": "bf16", + } + + +def adapt_bmm(inp: BatchGemmInput) -> dict: + """Adapt inputs for the torch.bmm (cuBLAS) reference.""" + return {"x": inp.x, "w": inp.w, "out": inp.out} + + +def adapt_fi(inp: BatchGemmInput, backend: str = "cudnn") -> dict: + """Inputs for flashinfer.bmm_bf16. + + It wants B as (b, k, n) column-major, which is exactly our (b, n, k) weight + transposed -- no copy, just strides on the tensor we already have. + """ + return { + "x": inp.x, + "bt": inp.w.transpose(-2, -1), + "out": inp.out, + "backend": backend, + } + + +def run_halops_batch(inp: dict): + """Run the HALOps batch GEMM kernel.""" + batch_gemm( + inp["x"], + inp["w"], + inp["sfa"], + inp["sfb"], + inp["out"], + bias=inp["bias"], + alpha=inp["alpha"], + sm_count=inp["sm_count"], + mode=inp["mode"], + ) + + +def run_bmm_reference(inp: dict): + """Reference: torch.bmm -> cuBLAS batch GEMM (what aten::bmm calls).""" + torch.bmm(inp["x"], inp["w"].transpose(-2, -1), out=inp["out"]) + + +def run_bmm_golden(inp: dict): + """Golden reference: bf16 matmul in fp32 accumulation.""" + x_f = inp["x"].float() + w_f = inp["w"].float().transpose(-2, -1) + inp["out"].copy_(torch.bmm(x_f, w_f).to(torch.bfloat16)) + + +def _get_backends(names: list[str]) -> dict: + registry = { + "golden": (adapt_bmm, run_bmm_golden), + "halops": (adapt_halops, run_halops_batch), + "fi": (partial(adapt_fi, backend="cudnn"), run_fi_batch_gemm), + "fi_cutlass": (partial(adapt_fi, backend="cutlass"), run_fi_batch_gemm), + "bmm": (adapt_bmm, run_bmm_reference), + } + backends = {} + for name in names: + if name in registry: + backends[name] = registry[name] + else: + print(f"[WARN] unknown backend '{name}', skipped") + return backends + + +def _bench_entry( + cfg, + name, + dry_run_iters, + repeat_iters, + cold_l2_cache, + use_cuda_graph, + timing_method, +): + """Subprocess entry: build inputs, adapt, bench a single backend.""" + b, m, n, k = cfg["b"], cfg["m"], cfg["n"], cfg["k"] + sm_count = cfg.get("sm_count", -1) + mode = cfg.get("mode", "bf16") + raw_inp = _build_inputs(b, m, n, k, sm_count, mode=mode) + backends = _get_backends([name]) + if name not in backends: + raise RuntimeError(f"backend '{name}' not found") + adapt_fn, run_fn = backends[name] + inp = adapt_fn(raw_inp) + + return bench_gpu_time( + run_fn, + (inp,), + dry_run_iters=dry_run_iters, + repeat_iters=repeat_iters, + cold_l2_cache=cold_l2_cache, + method=timing_method, + ) + + +def _refcheck_entry( + cfg, ordered_names, refcheck_reference, refcheck_atol=1e-2, refcheck_rtol=1e-2 +): + """Subprocess entry for refcheck: run all backends + golden, compare.""" + b, m, n, k = cfg["b"], cfg["m"], cfg["n"], cfg["k"] + sm_count = cfg.get("sm_count", -1) + mode = cfg.get("mode", "bf16") + raw_inp = _build_inputs(b, m, n, k, sm_count, mode=mode) + + backends = _get_backends(ordered_names) + golden_fn = run_bmm_golden + golden_inp = adapt_bmm(raw_inp) + golden_inp["out"].zero_() + golden_fn(golden_inp) + torch.cuda.synchronize() + ref_out = golden_inp["out"].clone() + + results = {} + for name in ordered_names: + if name not in backends or name == refcheck_reference: + continue + adapt_fn, run_fn = backends[name] + inp = adapt_fn(raw_inp) + inp["out"].zero_() + run_fn(inp) + torch.cuda.synchronize() + out = inp["out"] + if out.dim() == 2: # HALOps writes [M, B * N] + out = out.view(m, b, n).transpose(0, 1) + diff = (out.float() - ref_out.float()).abs() + tol = refcheck_atol + refcheck_rtol * ref_out.float().abs() + n_bad = (diff > tol).sum().item() + mismatch = 100.0 * n_bad / ref_out.numel() + from core.refcheck import RefcheckResult + + results[name] = RefcheckResult(passed=n_bad == 0, mismatch_pct=mismatch) + return results + + +def run_scenario(cfg: dict) -> None: + """Run the batch GEMM benchmark scenario.""" + mode = cfg.get("mode", "bf16") + out_path = cfg.get("output_path", "results/batch_bf16.csv") + case_tag = cfg.get("case_tag", "") + dry_run_iters = cfg.get("dry_run_iters", 10) + repeat_iters = cfg.get("repeat_iters", 50) + cold_l2_cache = cfg.get("cold_l2_cache", True) + timing_method = cfg.get("timing_method", "profiler") + backend_names = cfg.get("backends", ["halops"]) + do_refcheck = cfg.get("refcheck", True) + refcheck_reference = cfg.get("refcheck_reference", "golden") + refcheck_atol = cfg.get("refcheck_atol", 1e-2) + refcheck_rtol = cfg.get("refcheck_rtol", 1e-2) + use_subprocess = cfg.get("use_subprocess", True) + timeout = cfg.get("timeout", 120) + + os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) + dtype_bytes = 2 + dtype_str = "bf16" + + for shape in cfg["shapes"]: + b, m, n, k = shape + local_cfg = {**cfg, "b": b, "m": m, "n": n, "k": k} + + refcheck_results = {n_: None for n_ in backend_names} + if do_refcheck: + refcheck_results = run_refcheck_cross_backends( + _refcheck_entry, + local_cfg, + backend_names, + refcheck_reference, + refcheck_atol=refcheck_atol, + refcheck_rtol=refcheck_rtol, + use_subprocess=use_subprocess, + timeout=timeout, + probe_entry_func=_bench_entry, + ) + + first = True + baseline_us = None + for name in backend_names: + status, timing = run_bench_for_backend( + _bench_entry, + name, + local_cfg, + dry_run_iters, + repeat_iters, + cold_l2_cache, + False, # use_cuda_graph not used in GEMM + timing_method, + use_subprocess=use_subprocess, + timeout=timeout, + ) + if status != "OK": + print(f"[{status}] {name} b={b},m={m},n={n},k={k}") + continue + + metrics = compute_gemm_metrics( + timing, + b * m, # total M for FLOPs calculation + n, + k, + dtype_bytes=dtype_bytes, + baseline_us=baseline_us, + gpu_type=cfg.get("gpu_type", "b200"), + num_experts=b, # each expert loads [n, k] once + ) + if name == "halops": + baseline_us = metrics.median_us + rc = refcheck_results.get(name) + refcheck_pass = rc.passed if rc is not None else None + mismatch_pct = rc.mismatch_pct if rc is not None else None + row = GemmRowResult( + scenario="batch_gemm", + backend=name, + m=m, # per-batch-item M (total = b*m shown via num_experts) + n=n, + k=k, + mode=mode, + dtype=dtype_str, + metrics=metrics, + refcheck_pass=refcheck_pass, + case_tag=case_tag, + num_experts=b, + mismatch_pct=mismatch_pct, + ) + if first: + print_scenario_header(row) + print_table_header() + first = False + print_table_row(row) + append_gemm_csv(row, out_path) + + if not first: + print() diff --git a/benchmark/kernel/gemm/scenarios/dense_gemm.py b/benchmark/kernel/gemm/scenarios/dense_gemm.py index fa500ff..018f7fb 100644 --- a/benchmark/kernel/gemm/scenarios/dense_gemm.py +++ b/benchmark/kernel/gemm/scenarios/dense_gemm.py @@ -45,7 +45,7 @@ NVFP4_SF_BLOCK = 16 # group_wise_quant can also produce MXFP4 inputs, but this benchmark only # generates the FP8 and NVFP4 recipes (the kernel supports w4a4-mxfp4 too). -DENSE_MODES = ("w8a8-mxfp8", "w4a4-nvfp4") +DENSE_MODES = ("w8a8-mxfp8", "w4a4-nvfp4", "bf16") @dataclass @@ -81,6 +81,29 @@ def _build_inputs( ) is_nvfp4 = mode == "w4a4-nvfp4" + if mode == "bf16": + # Native BF16: no quantization, no scale factors, no alpha. The kernel + # consumes the bf16 source directly; x/w double as the golden source. + assert k % 64 == 0, f"k={k} must be divisible by 64 for bf16" + x_bf16 = torch.randn(m, k, dtype=torch.bfloat16, device=dev) + w_bf16 = torch.randn(n, k, dtype=torch.bfloat16, device=dev) + out = torch.empty(m, n, dtype=torch.bfloat16, device=dev) + return GemmInput( + x=x_bf16, + w=w_bf16, + sfa=None, + sfb=None, + out=out, + m=m, + n=n, + k=k, + sm_count=sm_count, + mode=mode, + x_bf16=x_bf16, + w_bf16=w_bf16, + alpha=None, + ) + if is_nvfp4: assert k % (2 * NVFP4_SF_BLOCK) == 0, f"k={k} must be divisible by 32" else: @@ -128,6 +151,13 @@ def adapt_halops(inp: GemmInput) -> dict: def adapt_fi(inp: GemmInput) -> dict: """Adapt inputs for FlashInfer backend.""" + if inp.mode == "bf16": + return { + "x": inp.x, + "w": inp.w, + "out": inp.out, + "mode": "bf16", + } if inp.mode == "w4a4-nvfp4": return { "x": inp.x, @@ -272,9 +302,17 @@ def run_scenario(cfg: dict) -> None: os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) - # Bytes per operand element for the bandwidth metric: FP8 = 1, FP4 = 0.5. - dtype_bytes = 0.5 if mode == "w4a4-nvfp4" else 1 - dtype_str = "fp4_e2m1" if mode == "w4a4-nvfp4" else "fp8_e4m3" + # Bytes per operand element for the bandwidth metric: FP8 = 1, FP4 = 0.5, + # BF16 = 2. + if mode == "bf16": + dtype_bytes = 2 + dtype_str = "bf16" + elif mode == "w4a4-nvfp4": + dtype_bytes = 0.5 + dtype_str = "fp4_e2m1" + else: + dtype_bytes = 1 + dtype_str = "fp8_e4m3" for shape in cfg["shapes"]: m, n, k = shape diff --git a/benchmark/kernel/gemm/scenarios/grouped_gemm.py b/benchmark/kernel/gemm/scenarios/grouped_gemm.py index 9dea119..3bbf86e 100644 --- a/benchmark/kernel/gemm/scenarios/grouped_gemm.py +++ b/benchmark/kernel/gemm/scenarios/grouped_gemm.py @@ -52,7 +52,7 @@ NVFP4_SF_BLOCK = 16 # The grouped kernels also support w4a4-mxfp4; this benchmark only generates # the FP8 and NVFP4 recipes. -GROUPED_MODES = ("w8a8-mxfp8", "w4a4-nvfp4") +GROUPED_MODES = ("w8a8-mxfp8", "w4a4-nvfp4", "bf16") @dataclass @@ -99,6 +99,17 @@ def _make_grouped_tensors(num_experts: int, max_m: int, n: int, k: int, mode: st ) is_nvfp4 = mode == "w4a4-nvfp4" + if mode == "bf16": + # Native BF16: no quantization, no scale factors, no alpha. x/w double + # as the golden source (returned as x_bf16 / w_bf16). + assert k % 64 == 0, f"k={k} must be divisible by 64 for bf16" + x_bf16 = torch.randn(m, k, dtype=torch.bfloat16, device=dev) + w_bf16_stacked = torch.randn( + num_experts, n, k, dtype=torch.bfloat16, device=dev + ) + out = torch.empty(m, n, dtype=torch.bfloat16, device=dev) + return x_bf16, w_bf16_stacked, None, None, out, None, x_bf16, w_bf16_stacked + if is_nvfp4: assert k % (2 * NVFP4_SF_BLOCK) == 0, f"k={k} must be divisible by 32" else: @@ -253,6 +264,7 @@ def adapt_fi(inp: GroupGemmInput, scenario: str = "masked") -> dict: "sfa": inp.sfa, "sfb": inp.sfb, "m_indptr": m_indptr, + "out": inp.out, "mode": inp.mode, } @@ -394,8 +406,15 @@ def run_group_masked(cfg: dict) -> None: refcheck_rtol = cfg.get("refcheck_rtol", 1e-2) os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) - dtype_bytes = 0.5 if mode == "w4a4-nvfp4" else 1 - dtype_str = "fp4_e2m1" if mode == "w4a4-nvfp4" else "fp8_e4m3" + if mode == "bf16": + dtype_bytes = 2 + dtype_str = "bf16" + elif mode == "w4a4-nvfp4": + dtype_bytes = 0.5 + dtype_str = "fp4_e2m1" + else: + dtype_bytes = 1 + dtype_str = "fp8_e4m3" for num_experts, max_m, n, k in cfg["shapes"]: active_m = num_experts * max_m @@ -498,8 +517,15 @@ def run_group_contiguous(cfg: dict) -> None: refcheck_rtol = cfg.get("refcheck_rtol", 1e-2) os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) - dtype_bytes = 0.5 if mode == "w4a4-nvfp4" else 1 - dtype_str = "fp4_e2m1" if mode == "w4a4-nvfp4" else "fp8_e4m3" + if mode == "bf16": + dtype_bytes = 2 + dtype_str = "bf16" + elif mode == "w4a4-nvfp4": + dtype_bytes = 0.5 + dtype_str = "fp4_e2m1" + else: + dtype_bytes = 1 + dtype_str = "fp8_e4m3" for requested_experts, max_m, n, k in cfg["shapes"]: m = requested_experts * max_m diff --git a/ci/baselines/gemm/batch_bf16.json b/ci/baselines/gemm/batch_bf16.json new file mode 100644 index 0000000..40216c4 --- /dev/null +++ b/ci/baselines/gemm/batch_bf16.json @@ -0,0 +1,133 @@ +{ + "config": "batch_bf16", + "op": "gemm", + "threshold": 0.05, + "entries": [ + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 8, + "max_m": "", + "m": 8192, + "n": 1024, + "k": 4096, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 348.236 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 8192, + "max_m": "", + "m": 64, + "n": 128, + "k": 4096, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 1888.814 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 8192, + "max_m": "", + "m": 64, + "n": 512, + "k": 576, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 912.394 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 8192, + "max_m": "", + "m": 64, + "n": 512, + "k": 64, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 192.414 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 8192, + "max_m": "", + "m": 64, + "n": 256, + "k": 64, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 100.035 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 8, + "max_m": "", + "m": 1024, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 184.657 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 8, + "max_m": "", + "m": 128, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 64.24 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 4, + "max_m": "", + "m": 256, + "n": 7168, + "k": 4096, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 62.082 + }, + { + "key": { + "scenario": "batch_gemm", + "backend": "halops", + "num_experts": 1, + "max_m": "", + "m": 8192, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "batch_bf16" + }, + "median_us": 170.864 + } + ] +} \ No newline at end of file diff --git a/ci/baselines/gemm/dense_bf16.json b/ci/baselines/gemm/dense_bf16.json new file mode 100644 index 0000000..175700f --- /dev/null +++ b/ci/baselines/gemm/dense_bf16.json @@ -0,0 +1,147 @@ +{ + "config": "dense_bf16", + "op": "gemm", + "threshold": 0.05, + "entries": [ + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 64, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 10.832 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 64, + "n": 32768, + "k": 1024, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 16.944 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 128, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 12.352 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 128, + "n": 128, + "k": 4096, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 7.136 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 256, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 14.753 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 1024, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 27.393 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 1024, + "n": 1600, + "k": 4096, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 16.128 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 1024, + "n": 32768, + "k": 1024, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 49.056 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 4096, + "n": 4096, + "k": 4096, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 93.153 + }, + { + "key": { + "scenario": "dense_gemm", + "backend": "halops", + "num_experts": "", + "max_m": "", + "m": 8192, + "n": 32768, + "k": 1024, + "mode": "bf16", + "case_tag": "dense_bf16" + }, + "median_us": 335.369 + } + ] +} \ No newline at end of file diff --git a/csrc/kernel/gemm/batch_gemm.cu b/csrc/kernel/gemm/batch_gemm.cu index 12f7549..039ef5d 100644 --- a/csrc/kernel/gemm/batch_gemm.cu +++ b/csrc/kernel/gemm/batch_gemm.cu @@ -15,6 +15,7 @@ #include #include +#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -29,9 +30,10 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, const std::optional& gate, const bool use_pdl) { const CudaDeviceGuard device_guard(input.device()); TORCH_CHECK( - mode == "w8a8-mxfp8" || mode == "w4a4-nvfp4" || mode == "w4a4-mxfp4", + mode == "bf16" || mode == "w8a8-mxfp8" || mode == "w4a4-nvfp4" || + mode == "w4a4-mxfp4", "Unsupported mode: ", mode, - ". Expected 'w8a8-mxfp8', 'w4a4-nvfp4' or 'w4a4-mxfp4'."); + ". Expected 'bf16', 'w8a8-mxfp8', 'w4a4-nvfp4' or 'w4a4-mxfp4'."); TORCH_CHECK(input.dim() == 3, "input must be a 3D tensor of shape [B, M, K]"); TORCH_CHECK(weight.dim() == 3, @@ -66,7 +68,48 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.max_m_per_expert = m; params.use_pdl = use_pdl; - if (mode == "w8a8-mxfp8") { + if (mode == "bf16") { + using TypeA = cutlass::bfloat16_t; + using TypeB = cutlass::bfloat16_t; + using TypeC = cutlass::bfloat16_t; + using TypeD = cutlass::bfloat16_t; + using TypeSF = cutlass::float_ue8m0_t; // placeholder, unused + using TypeAccumulate = float; + + const int k = weight.size(2); + TORCH_CHECK(input.size(2) == k, + "input K must match weight K, got input K=", input.size(2), + ", weight K=", k); + TORCH_CHECK(input.dtype() == torch::kBFloat16, + "bf16 batch GEMM: input must be bfloat16"); + TORCH_CHECK(weight.dtype() == torch::kBFloat16, + "bf16 batch GEMM: weight must be bfloat16"); + TORCH_CHECK(output.dtype() == torch::kBFloat16, + "bf16 batch GEMM: output must be bfloat16"); + TORCH_CHECK(epilogue == EpilogueOp::Identity && + !output_sf.has_value() && !gate.has_value(), + "bf16 batch GEMM supports EpilogueOp.Identity only"); + params.k = k; + params.ptr_a = input.data_ptr(); + params.ptr_b = weight.data_ptr(); + params.ptr_sfa = nullptr; + params.ptr_sfb = nullptr; + params.ptr_alpha = nullptr; + + const int cfg = bf16_dispatch::SelectBF16BatchCfg(m, n, k); + TORCH_CHECK(cfg >= 0, "bf16 batch GEMM: unsupported shape B=", batches, + " M=", m, " N=", n, " K=", k, + ". Need one of: (M%256==0 && N%256==0), " + "(M%128==0 && N%256==0), or (M%64==0 && N%128==0)."); + bf16_dispatch::CheckBF16CfgShape( + "bf16 batch GEMM", bf16_dispatch::kBF16BatchCfgs[cfg], m, n, k); + bf16_dispatch::DispatchBF16SmallCfg( + cfg, "bf16 batch", [&]() { + gemm_impl(params, sm, stream); + }); + } else if (mode == "w8a8-mxfp8") { const int k = weight.size(2); TORCH_CHECK(input.size(2) == k, "input K must match weight K, got input K=", input.size(2), diff --git a/csrc/kernel/gemm/bf16_cfgs.h b/csrc/kernel/gemm/bf16_cfgs.h new file mode 100644 index 0000000..e0a2066 --- /dev/null +++ b/csrc/kernel/gemm/bf16_cfgs.h @@ -0,0 +1,1015 @@ +// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// =========================================================================== +// BF16 dense/grouped/batch dispatch: the shape-aware ladder moved verbatim +// from the DenseGemm/GroupContiguousGemm/GroupMaskedGemm/BatchGemm host +// functions. Unlike the W8A8 cost model (SelectDenseCfg above), the BF16 +// ladder is rule-based (pair-UMMA CTA bands, stream-K, k-tile depth gates, +// wave-fill judgements) -- the same shape as SelectW4A4Cfg, just longer. +// Selectors return a catalog id; DispatchBF16*Cfg maps ids to instantiations. +// =========================================================================== + +#pragma once + +#include +#include +#include +#include + +#include "kernel/gemm/gemm_tile.cuh" +#include "kernel/gemm/gemm_utils.h" + +namespace halops { +namespace bf16_dispatch { + +// --------------------------------------------------------------------------- +// Shared helpers (verbatim from the old dense_gemm.cu anonymous namespace). +// --------------------------------------------------------------------------- + +constexpr int64_t kPairDeepMinCtas = 40; +constexpr int64_t kPairDeepMaxCtas = 152; + +constexpr int64_t CeilDiv(int64_t x, int64_t d) { return (x + d - 1) / d; } + +// KBlockK of every BF16 config below. +constexpr int64_t kBF16BlockK = 64; + +// Deep-prologue configs (14/18 stages) only help with at least this many +// K-tiles. +constexpr int64_t kDeepPrologueMinKTiles = 32; + +inline bool DeepProloguePays(int k) { + return k / kBF16BlockK >= kDeepPrologueMinKTiles; +} + +inline int64_t PairDeepCtaCount(int m, int n) { + return 2 * CeilDiv(m, 128) * CeilDiv(n, 64); +} + +inline void CheckPairDeepCtaBand(int m, int n, int cluster4_arm) { + // HALOPS_PAIR_UNSAFE=1 lifts the guard (debugging only). + static const bool unsafe_ok = [] { + const char* e = std::getenv("HALOPS_PAIR_UNSAFE"); + return e != nullptr && e[0] == '1'; + }(); + if (unsafe_ok) { + return; + } + const int64_t ctas = PairDeepCtaCount(m, n); + TORCH_CHECK(ctas >= kPairDeepMinCtas && ctas <= kPairDeepMaxCtas, + "HALOPS_CLUSTER4=", cluster4_arm, + " selects the 2SM/KBlockM=128 pair-UMMA family, which is still " + "numerically WRONG outside a CTA count of [", + kPairDeepMinCtas, ", ", kPairDeepMaxCtas, + "]. This shape (m=", m, ", n=", n, ") gives ", ctas, + " CTAs; refusing rather than " + "returning silently wrong results."); +} + +// For m < 128: use a non-SwapAB KBlockM=64 tile when even SwapAB's smallest +// tile leaves SMs idle. HALOPS_M64_NOSWAP=0 always uses SwapAB. +inline bool ThinMNoSwapOk(int m, int n, int k, int sm_count) { + static const bool disabled = [] { + const char* e = std::getenv("HALOPS_M64_NOSWAP"); + return e != nullptr && e[0] == '0'; + }(); + if (disabled) { + return false; + } + if (m % 64 != 0 || k % 64 != 0) { + return false; + } + const int target = ResolveSmCount(sm_count); + const int64_t nt32 = CeilDiv(n, 32); + const int64_t mt = CeilDiv(m, 64); + const bool narrow_ok = (n % 32 == 0) && (nt32 * mt <= target); + const bool square_ok = (n % 64 == 0); + if (!narrow_ok && !square_ok) { + return false; + } + const int64_t swapab_tiles = CeilDiv(n, 128) * CeilDiv(m, 32); + return swapab_tiles < target; +} + +// Above this many K-tiles keep 256x256: 256x128 re-reads A twice as often, +// which outweighs any wave-packing gain. +constexpr int64_t kPairFineNMaxKTiles = 64; + +// Minimum K-tiles for the deep-prologue mid-M configs (64x96 P11, 128x64 pair +// P18). +constexpr int64_t kMidMDeepPrologueMinKTiles = 54; + +// True if fine_ctas keeps a larger fraction of SMs busy than coarse_ctas, +// where busy fraction = ctas / (target * number_of_waves). +inline bool PacksTailTighter(int64_t coarse_ctas, int64_t fine_ctas, + int64_t target) { + const int64_t coarse_waves = (coarse_ctas + target - 1) / target; + const int64_t fine_waves = (fine_ctas + target - 1) / target; + return fine_ctas * coarse_waves > coarse_ctas * fine_waves; +} + +// HALOPS_PAIR_FINE_N=0 disables PreferFinePairN at both call sites. +inline bool PairFineNDisabled() { + static const bool disabled = [] { + const char* e = std::getenv("HALOPS_PAIR_FINE_N"); + return e != nullptr && e[0] == '0'; + }(); + return disabled; +} + +// Use 256x128 instead of 256x256 for the pair-UMMA tile when K is short and +// 256x128 keeps more SMs busy; beyond 4 waves the gain is negligible. +inline bool PreferFinePairN(int n, int k, int64_t coarse_ctas, + int64_t fine_ctas, int64_t target) { + return (n % 128 == 0) && (k / 64 <= kPairFineNMaxKTiles) && + (coarse_ctas <= 4 * target) && + PacksTailTighter(coarse_ctas, fine_ctas, target); +} + +// ---- Small-N tiles (N <= 128) ---------------------------------------------- +// N fits in a single tile, so all CTAs must come from splitting M. Pick the +// largest tile whose CTA count is within (0.5, 1.0] of one wave. +// HALOPS_SMALL_N=0 disables this. +inline bool SmallNLadderDisabled() { + static const bool disabled = [] { + const char* e = std::getenv("HALOPS_SMALL_N"); + return e != nullptr && e[0] == '0'; + }(); + return disabled; +} + +enum class SmallNTile { + kNone, + kPairM256N128, + kM64N128, + kPairM256N64, + kM64N64, +}; + +constexpr int64_t kSmallNMaxN = 128; +constexpr int64_t kSmallNAlignN = 64; + +inline bool FillsOneWave(int64_t ctas, int64_t target) { + return ctas <= target && 2 * ctas > target; +} + +struct SmallNRung { + SmallNTile tile; + int64_t block_m; + int64_t block_n; + int64_t ctas_per_cluster; +}; + +inline SmallNTile PickSmallNTile(int m, int n, int64_t target) { + if (SmallNLadderDisabled() || n > kSmallNMaxN || n % kSmallNAlignN != 0) { + return SmallNTile::kNone; + } + static constexpr SmallNRung kRungs[] = { + {SmallNTile::kPairM256N128, 256, 128, 2}, + {SmallNTile::kM64N128, 64, 128, 1}, + {SmallNTile::kPairM256N64, 256, 64, 2}, + {SmallNTile::kM64N64, 64, 64, 1}, + }; + for (const SmallNRung& r : kRungs) { + const int64_t ctas = + r.ctas_per_cluster * CeilDiv(m, r.block_m) * CeilDiv(n, r.block_n); + if (FillsOneWave(ctas, target)) { + return r.tile; + } + } + // No tile fits; use the regular large-M dispatch. + return SmallNTile::kNone; +} + +// --------------------------------------------------------------------------- +// Environment-variable knobs, read once per process (static locals). +// --------------------------------------------------------------------------- + +inline bool EnvIs(const char* name, const char* value) { + const char* e = std::getenv(name); + return e != nullptr && e[0] == value[0]; +} + +inline bool EnvNot0(const char* name) { + const char* e = std::getenv(name); + return e == nullptr || e[0] != '0'; +} + +inline int EnvIntOr(const char* name, int fallback) { + const char* e = std::getenv(name); + return e != nullptr ? atoi(e) : fallback; +} + +inline int64_t EnvInt64Or(const char* name, int64_t fallback) { + const char* e = std::getenv(name); + return e != nullptr ? static_cast(atoll(e)) : fallback; +} + +// --------------------------------------------------------------------------- +// Dense (Naive) catalog. Order defines the id; ids are only meaningful +// together with DispatchBF16Cfg below (both index the same tuple). +// --------------------------------------------------------------------------- + +using BF16Tiles = + cute::tuple; // 34 +constexpr int kBF16CfgCount = static_cast(cute::tuple_size_v); + +// Index of a tile in the catalog (dispatch names tiles by type; reordering +// the list cannot silently re-point an id). +template +constexpr int BF16TileIndex() { + if constexpr (I < kBF16CfgCount) { + if constexpr (cute::is_same, + T>::value) { + return I; + } else { + return BF16TileIndex(); + } + } else { + static_assert(I < 0, "tile is not in BF16Tiles"); + return -1; + } +} + +// Shape descriptor for host-side divisibility checks after selection. +struct BF16CfgDesc { + int bm; // KBlockM (for SwapAB: the weight M) + int bn; // KBlockN (for SwapAB: the activation extent) + int bk; // KBlockK + bool swap; // SwapAB + bool ntail; // KForceEpiNPredicate: N only needs % 64 (or % 32 for + // non-power-of-2 KBlockN) +}; + +template +constexpr BF16CfgDesc MakeBF16Desc() { + return {T::KBlockM, T::KBlockN, T::KBlockK, T::SwapAB, + T::KForceEpiNPredicate}; +} + +template +constexpr std::array MakeBF16Table( + std::index_sequence) { + return {{MakeBF16Desc>()...}}; +} + +constexpr auto kBF16Cfgs = + MakeBF16Table(std::make_index_sequence{}); + +// --------------------------------------------------------------------------- +// SelectBF16Cfg: the dense ladder, moved verbatim from dense_gemm.cu. +// Returns a BF16Tiles catalog id or -1 when no rung supports the shape. +// The caller validates divisibility against kBF16Cfgs[id] and launches via +// DispatchBF16Cfg. +// --------------------------------------------------------------------------- + +namespace dense { + +using bf16_dispatch::CeilDiv; +using bf16_dispatch::CheckPairDeepCtaBand; +using bf16_dispatch::DeepProloguePays; +using bf16_dispatch::EnvInt64Or; +using bf16_dispatch::EnvIntOr; +using bf16_dispatch::EnvIs; +using bf16_dispatch::EnvNot0; +using bf16_dispatch::kBF16BlockK; +using bf16_dispatch::kMidMDeepPrologueMinKTiles; +using bf16_dispatch::PacksTailTighter; +using bf16_dispatch::PairDeepCtaCount; +using bf16_dispatch::PairFineNDisabled; +using bf16_dispatch::PickSmallNTile; +using bf16_dispatch::PreferFinePairN; +using bf16_dispatch::SmallNTile; +using bf16_dispatch::ThinMNoSwapOk; + +inline int SelectBF16Cfg(int m, int n, int k, int sm_count) { + if (m >= 4096) { + // Large-M: 256x256 pair tile by default, or 256x128 (deeper + // pipeline) when PreferFinePairN says so. If n % 256 != 0, fall + // back to 256x128, then _Ntail / 256x64; n % 64 != 0 is rejected. + const int target_sm = ResolveSmCount(sm_count); + switch (PickSmallNTile(m, n, target_sm)) { + case SmallNTile::kM64N128: + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA>(); + case SmallNTile::kM64N64: { + // HALOPS_SMALLN_1WG_DEEP=0 restores 2WG/10 stages. + static const bool smalln_1wg_deep = + EnvNot0("HALOPS_SMALLN_1WG_DEEP"); + if (smalln_1wg_deep && DeepProloguePays(k)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA>(); + } + case SmallNTile::kPairM256N64: + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA>(); + // Handled by the default dispatch below. + case SmallNTile::kPairM256N128: + case SmallNTile::kNone: + break; + } + const int64_t tiles_256 = CeilDiv(m, 256) * CeilDiv(n, 256); + const int64_t mt_256 = CeilDiv(m, 256); + const bool square_like = + PairFineNDisabled() + ? ((n % 128 == 0) && (tiles_256 <= 2 * target_sm)) + : PreferFinePairN(n, k, 2 * tiles_256, + 2 * mt_256 * CeilDiv(n, 128), target_sm); + // HALOPS_LARGEM_DEEP=0 restores the shallower P6/P8 configs. + static const bool largem_deep = EnvNot0("HALOPS_LARGEM_DEEP"); + if (square_like) { + return largem_deep + ? bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9>() + : bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA>(); + } + if (n % 256 == 0) { + return largem_deep + ? bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA_P7>() + : bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA>(); + } + if (n % 128 == 0) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA>(); + } + // n % 128 != 0 (e.g. 1600): 128-wide _Ntail tile, which masks + // the store of the partial last tile. HALOPS_LARGEM_NTAIL=0 + // uses 256x64 instead. + static const bool largem_ntail_disabled = + EnvIs("HALOPS_LARGEM_NTAIL", "0"); + if (!largem_ntail_disabled && (n % 64 == 0)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA>(); + } + + if (m >= 128) { + // The narrowest mid-M tile is 128x32, so only n % 32 is needed. + if (m % 128 != 0 || n % 32 != 0 || k % 64 != 0) { + return -1; + } + + // HALOPS_CLUSTER4=1..5 forces a clustered 128x64 pair variant + // (debugging only; checked against the trusted CTA band). + static const int cluster4 = EnvIntOr("HALOPS_CLUSTER4", 0); + if (cluster4 != 0 && (m % 128 == 0) && (n % 128 == 0) && + (k % 64 == 0)) { + CheckPairDeepCtaBand(m, n, cluster4); + switch (cluster4) { + case 1: + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA>(); + case 3: + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P16>(); + case 4: + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18>(); + case 5: + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18>(); + default: + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_2x1CTA>(); + } + } + + // ---- KBlockM=64 tiles (64x64 / 64x32) -------------------------- + // Smaller tiles add CTAs, but with no multicast each extra N-tile + // reloads A. Use them only if the grid fits one wave and the A + // reload volume k_tiles * n_tiles is within rereads_cap. + // HALOPS_TILE_M64=0 disables them. + static const bool m64_disabled = EnvIs("HALOPS_TILE_M64", "0"); + if (!m64_disabled && (m % 64 == 0) && (n % 64 == 0) && (k % 64 == 0)) { + const int sm = ResolveSmCount(sm_count); + const int64_t tiles64 = CeilDiv(m, 64) * CeilDiv(n, 64); + const int64_t rereads = (k / kBF16BlockK) * CeilDiv(n, 64); + // HALOPS_REREADS_CAP= overrides the re-read cap. + static const int64_t rereads_cap = + EnvInt64Or("HALOPS_REREADS_CAP", 2048); + // HALOPS_FORCE_M64_N32=1 uses 64x32 regardless of both + // limits. + static const bool n32_force = EnvIs("HALOPS_FORCE_M64_N32", "1"); + if (n32_force || (tiles64 <= sm && rereads <= rereads_cap)) { + // 1-epilogue-WG configs: required for 64x32 (KEpiComputeN + // must be >= 32) and free of the inter-WG barrier. Use + // 64x32 if twice the 64x64 tile count still fits one wave, + // else 64x64. HALOPS_M64_1WG=0 uses the 2WG 64x64. + static const bool wg1_disabled = EnvIs("HALOPS_M64_1WG", "0"); + if (!wg1_disabled) { + if ((n32_force || 2 * tiles64 <= sm) && (n % 32 == 0)) { + // HALOPS_N32_STAGES=10|14|18 forces the stage + // count. + static const int n32_stages = + EnvIntOr("HALOPS_N32_STAGES", 0); + const bool deep = n32_stages == 0 ? DeepProloguePays(k) + : n32_stages == 18; + if (n32_stages == 14) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P14_1CTA>(); + } + if (deep) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_1CTA>(); + } + // HALOPS_M64_1WG_DEEP=0 restores 10 stages. + static const bool m64_1wg_deep = + EnvNot0("HALOPS_M64_1WG_DEEP"); + if (m64_1wg_deep && DeepProloguePays(k)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA>(); + } + // HALOPS_M64_STAGES=12|14 uses a deeper 2WG 64x64. + static const int m64_stages = EnvIntOr("HALOPS_M64_STAGES", 0); + if (m64_stages == 12) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_P12_1CTA>(); + } + if (m64_stages == 14) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_P14_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA>(); + } + } + + // ---- 128xN tiles ------------------------------------------------ + // Halve N (256 -> 128 -> 64 -> 32) while the current tile leaves + // SMs idle. + const int target = ResolveSmCount(sm_count); + auto tiles = [&](int tm, int tn) { + return ((m + tm - 1) / tm) * ((n + tn - 1) / tn); + }; + // HALOPS_DISABLE_TILE_N32=1 stops at 128x64. + static const bool n32_disabled = EnvIs("HALOPS_DISABLE_TILE_N32", "1"); + // pick: 0=128x256, 1=128x128, 2=128x64, 3=128x32. + int pick; + if (n % 256 == 0) { + pick = 0; + } else if (n % 128 == 0) { + pick = 1; + } else if (n % 64 == 0) { + pick = 2; + } else { + pick = 3; + } + // Keep 128x256 if it already fills half a wave and 128x128 would + // spill into a second wave. + const bool overshoots_128 = + m > 128 && tiles(128, 128) > target && 2 * tiles(128, 256) > target; + if (pick == 0 && tiles(128, 256) < target && (n % 128 == 0) && + !overshoots_128) { + pick = 1; // 128x128 + } + if (pick == 1 && tiles(128, 128) < target && (n % 64 == 0)) { + pick = 2; // 128x64 + } + if (pick == 2 && !n32_disabled && tiles(128, 64) < target && + (n % 32 == 0)) { + pick = 3; // 128x32 + } + + // ---- 256xN pair-UMMA tiles (m % 256 == 0) ---------------------- + // Same CTA count as 128xN, but B is loaded half as often. Used + // only if: + // 1) k_tiles >= 3 * KPrologueStages, or the grid is >= 1 wave; + // 2) for 256x64, the grid is >= 0.8 wave. + // HALOPS_MIDM_PAIR=0 disables them. + static const bool midm_pair = EnvNot0("HALOPS_MIDM_PAIR"); + if (midm_pair && (m % 256 == 0) && (n % 64 == 0) && (k % 64 == 0)) { + auto pair_ctas = [&](int64_t tn) { + return static_cast(m / 256) * ((n + tn - 1) / tn) * 2; + }; + // Halve N only while the grid is under one wave, and never + // from >= half a wave into more than one wave. + auto step_ok = [&](int64_t coarse, int64_t fine) { + return pair_ctas(coarse) < target && + !(pair_ctas(fine) > target && + 2 * pair_ctas(coarse) > target); + }; + int pair_tn = (n % 256 == 0) ? 256 : ((n % 128 == 0) ? 128 : 64); + // n % 128 != 0 (e.g. 1600): use the 128-wide _Ntail tile + // instead of 64 if it fills at least half a wave. + // HALOPS_MIDM_NTAIL=0 disables it. + static const bool midm_ntail = EnvNot0("HALOPS_MIDM_NTAIL"); + bool pair_n_tail = false; + if (midm_ntail && pair_tn == 64 && (n % 128 != 0) && + 2 * pair_ctas(128) >= target) { + pair_tn = 128; + pair_n_tail = true; + } + // Also use 128 when PreferFinePairN says so (multi-wave). + if (pair_tn == 256 && (n % 128 == 0) && + (step_ok(256, 128) || + (!PairFineNDisabled() && + PreferFinePairN(n, k, pair_ctas(256), pair_ctas(128), + target)))) { + pair_tn = 128; + } + // Use 192 if it fits one wave and keeps more SMs busy than + // both 256 and 128. HALOPS_MIDM_PAIR192=0 disables it. + static const bool midm_pair192 = EnvNot0("HALOPS_MIDM_PAIR192"); + if (midm_pair192 && pair_tn != 64 && (n % 32 == 0) && + pair_ctas(192) <= target && + PacksTailTighter(pair_ctas(256), pair_ctas(192), target) && + PacksTailTighter(pair_ctas(128), pair_ctas(192), target)) { + pair_tn = 192; + pair_n_tail = false; + } + if (!pair_n_tail && pair_tn == 128 && (n % 64 == 0) && + step_ok(128, 64)) { + pair_tn = 64; + } + const int64_t pair_cta_count = pair_ctas(pair_tn); + const int64_t pair_k_tiles = k / 64; + const int pair_stages = + (pair_tn == 256) + ? GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA:: + KPrologueStages + : ((pair_tn == 192) + ? GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA:: + KPrologueStages + : ((pair_tn == 128) + ? GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA:: + KPrologueStages + : GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA:: + KPrologueStages)); + const bool amortizes_prologue = + pair_k_tiles >= 3 * pair_stages || pair_cta_count >= target; + const bool narrow_arm_fills = + pair_tn != 64 || 5 * pair_cta_count >= 4 * target; + // If n % 128 != 0 forced 256x64 and it spills past one wave, + // skip the pair tiles and let 64x96 / 64x224 below handle it. + const int64_t narrow_ctas96 = CeilDiv(m, 64) * CeilDiv(n, 96); + const int64_t narrow_ctas224 = CeilDiv(m, 64) * CeilDiv(n, 224); + const bool ninety_six_legal = + (m % 64 == 0) && (n % 32 == 0) && + (k / kBF16BlockK) >= kMidMDeepPrologueMinKTiles; + const bool two_two_four_legal = (m % 64 == 0) && (n % 32 == 0); + const bool narrow_arm_overshoots = + pair_tn == 64 && pair_cta_count > target && + two_two_four_legal && + (!ninety_six_legal || + PacksTailTighter(narrow_ctas224, narrow_ctas96, target)); + if (amortizes_prologue && narrow_arm_fills && + !narrow_arm_overshoots) { + if (pair_tn == 256) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA>(); + } + if (pair_tn == 192) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA>(); + } + if (pair_tn == 128) { + // HALOPS_MIDM_PAIR_DEEP=0 restores P8. + static const bool midm_pair_deep = + EnvNot0("HALOPS_MIDM_PAIR_DEEP"); + if (pair_n_tail) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9>(); + } + // With <= 32 K-tiles, 128x64x64_1CTA (same CTA count) is + // faster than 256x64 pair. HALOPS_MIDM_PAIR64_1CTA=0 + // disables it. + static const bool midm_pair64_1cta = + EnvNot0("HALOPS_MIDM_PAIR64_1CTA"); + if (midm_pair64_1cta && pair_k_tiles <= 32) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA>(); + } + } + + // If the 128xN tile spills past one wave, use 64x128 when that + // fits in one wave. HALOPS_DISABLE_WAVE64=1 disables it; + // HALOPS_WAVE64_ANYCTA=1 drops the one-wave condition. + static const bool wave64_disabled = EnvIs("HALOPS_DISABLE_WAVE64", "1"); + static const bool wave64_anycta = EnvIs("HALOPS_WAVE64_ANYCTA", "1"); + const int64_t pick_tn = + pick == 0 ? 256 : (pick == 1 ? 128 : (pick == 2 ? 64 : 32)); + // ---- 64x96 / 64x224 tiles -------------------------------------- + // Power-of-2 N widths can miss one wave entirely (n=7168: 112 or + // 224 CTAs on 152 SMs); 96/224 land in between. + // HALOPS_DISABLE_TILE96 / _TILE224 disable them. + static const bool tile96_disabled = EnvIs("HALOPS_DISABLE_TILE96", "1"); + static const bool tile224_disabled = + EnvIs("HALOPS_DISABLE_TILE224", "1"); + auto ctas_at = [&](int64_t tn) { + return CeilDiv(m, 64) * CeilDiv(n, tn); + }; + const int64_t ctas96 = ctas_at(96); + const int64_t ctas224 = ctas_at(224); + const int64_t incumbent_ctas = + (n % 128 == 0 && tiles(128, pick_tn) > target && + tiles(64, 128) <= target) + ? tiles(64, 128) + : tiles(128, pick_tn); + // c fits in one wave at > 50%, and either the current choice + // needs more than one wave or c gives more CTAs. + auto fills_better = [&](int64_t c) { + return c <= target && 2 * c > target && + (incumbent_ctas > target || c > incumbent_ctas); + }; + // The 256x64 pair tile above was skipped in favour of 64x96; + // take 64x96 even though it exceeds one wave. + const bool pair_deferred_to_96 = + (m % 256 == 0) && (n % 64 == 0) && (n % 128 != 0) && + (k % 64 == 0) && + (static_cast(m / 256) * CeilDiv(n, 64) * 2 > target); + if (!tile96_disabled && (m % 64 == 0) && (n % 32 == 0) && + (fills_better(ctas96) || pair_deferred_to_96) && + (k / kBF16BlockK) >= kMidMDeepPrologueMinKTiles) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x96x64_1CTA_P11>(); + } + if (!tile224_disabled && (m % 64 == 0) && (n % 32 == 0) && + fills_better(ctas224)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x224x64_1CTA_P6>(); + } + + if (!wave64_disabled && (m % 64 == 0) && (n % 128 == 0) && + tiles(128, pick_tn) > target && + (wave64_anycta || tiles(64, 128) <= target)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA>(); + } + + // ---- 128x64 pair-UMMA, 18 stages -------------------------------- + // Used when the grid is one wave with enough K-tiles, or when the + // 128xN choice is 128x128 (only 4 stages). Its CTA count stays in + // the correct band. HALOPS_DISABLE_PAIR_DEEP=1 disables it. + static const bool pairdeep_disabled = + EnvIs("HALOPS_DISABLE_PAIR_DEEP", "1"); + if (!pairdeep_disabled && (m % 128 == 0) && (n % 128 == 0) && + (k % 64 == 0)) { + const int pd_target = ResolveSmCount(sm_count); + const int64_t pair_ctas = PairDeepCtaCount(m, n); + const int64_t pair_k_tiles = k / kBF16BlockK; + const bool one_wave = + pair_ctas <= pd_target && 2 * pair_ctas > pd_target; + const bool deep_enough = pair_k_tiles >= kMidMDeepPrologueMinKTiles; + const bool shallow_incumbent = (pick == 1); + if ((one_wave && deep_enough) || shallow_incumbent) { + // With <= 64 K-tiles, 64x64x64_1WG_P14 is faster. + // HALOPS_PAIRDEEP_SHORTK=0 disables it. + static const bool pairdeep_shortk = + EnvNot0("HALOPS_PAIRDEEP_SHORTK"); + if (pairdeep_shortk && one_wave && deep_enough && + pair_k_tiles <= 64 && (m % 64 == 0) && (n % 64 == 0)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18>(); + } + } + if (pick == 3) { + // HALOPS_TILE_K32=1 swaps in 128x32x32 (16 stages). + static const bool k32_enabled = EnvIs("HALOPS_TILE_K32", "1"); + if (k32_enabled && (k % 32 == 0)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x32x32_1CTA>(); + } + // HALOPS_THINM_STAGES=4|6 forces a shallower prologue. + static const int thinm_stages = EnvIntOr("HALOPS_THINM_STAGES", 0); + if (thinm_stages == 4) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x32x64_P4_1CTA>(); + } + if (thinm_stages == 6) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x32x64_P6_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x32x64_1CTA>(); + } + if (pick == 2) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA>(); + } + if (pick == 1) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x128x64_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x256x64_1CTA>(); + } + + if (ThinMNoSwapOk(m, n, k, sm_count)) { + // ---- m < 128 without SwapAB ------------------------------------ + // At m=64 SwapAB yields too few CTAs; KBlockM=64 tiles give + // ceil(n/32). Use 64x32 if it fits one wave, else 64x64. + const int target = ResolveSmCount(sm_count); + const int64_t mt = CeilDiv(m, 64); + const int64_t nt32 = CeilDiv(n, 32); + if (nt32 * mt <= target && (n % 32 == 0)) { + if (DeepProloguePays(k)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_1CTA>(); + } + // HALOPS_M64_1WG_DEEP=0 restores the 10-stage config. + static const bool thin_1wg_deep = EnvNot0("HALOPS_M64_1WG_DEEP"); + if (thin_1wg_deep && DeepProloguePays(k)) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA>(); + } + + // Small-N SwapAB: weight (N×K) → UMMA A (M-dim=128), activation + // (M×K) → UMMA B (N-dim=64). + if (n % 128 != 0 || m % 64 != 0 || k % 64 != 0) { + return -1; + } + // Use KBlockK=128 for k >= 8192. HALOPS_DISABLE_SWAPAB_K128=1 + // disables it. + static const bool swapab_k128_disabled = + EnvIs("HALOPS_DISABLE_SWAPAB_K128", "1"); + if (!swapab_k128_disabled && (k % 128 == 0) && k >= 8192) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA>(); + } + // Use the 256-wide pair tile when the 128-wide grid exceeds 2 + // waves. HALOPS_DISABLE_SWAPAB_N256=1 disables it. + static const bool swapab_n256_disabled = + EnvIs("HALOPS_DISABLE_SWAPAB_N256", "1"); + const int swapab_target = ResolveSmCount(sm_count); + const int64_t swapab_tiles128 = CeilDiv(n, 128) * CeilDiv(m, 64); + if (!swapab_n256_disabled && (n % 256 == 0) && + swapab_tiles128 > 2 * swapab_target) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias256x64x64_SwapAB_2CTA>(); + } + // Use KBlockN=32 if that still fits one wave. + // HALOPS_DISABLE_SWAPAB_N32=1 disables it. + static const bool swapab_n32_disabled = + EnvIs("HALOPS_DISABLE_SWAPAB_N32", "1"); + const int64_t swapab_tiles64 = CeilDiv(n, 128) * CeilDiv(m, 32); + if (!swapab_n32_disabled && swapab_tiles64 <= swapab_target) { + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x32x64_SwapAB_1CTA>(); + } + return bf16_dispatch::BF16TileIndex< + GemmKernelConfigBF16NaiveNoBias128x64x64_SwapAB_1CTA>(); +} + +} // namespace dense + +// --------------------------------------------------------------------------- +// Grouped/batch catalogs and selectors (moved verbatim from their .cu +// host functions). +// --------------------------------------------------------------------------- + +using BF16ContiguousTiles = cute::tuple< + GemmKernelConfigBF16ContiguousNoBias256x256x64_2CTA, // 0 + GemmKernelConfigBF16ContiguousNoBias256x128x64_2CTA, // 1 + GemmKernelConfigBF16ContiguousNoBias128x256x64_1CTA, // 2 + GemmKernelConfigBF16ContiguousNoBias128x128x64_1CTA, // 3 + GemmKernelConfigBF16ContiguousNoBias128x64x64_1CTA, // 4 + GemmKernelConfigBF16ContiguousNoBias128x64x64_SwapAB_1CTA>; // 5 +constexpr int kBF16ContiguousCount = + static_cast(cute::tuple_size_v); + +using BF16MaskedTiles = + cute::tuple; // 5 +constexpr int kBF16MaskedCount = + static_cast(cute::tuple_size_v); + +using BF16BatchTiles = + cute::tuple; // 2 +constexpr int kBF16BatchCount = + static_cast(cute::tuple_size_v); + +// group_contiguous: m is the total token count. +inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { + if (m >= 4096) { + return 0; + } + if (m >= 128) { + // Step finer on N only while the coarser tile underfills the SM + // grid. M stays 128 (BF16 dummy-SF 1-CTA MMA requires M==128). + const int target_sm = ResolveSmCount(sm_count); + auto tiles = [&](int tm, int tn) { + return ((m + tm - 1) / tm) * ((n + tn - 1) / tn); + }; + // Step 0: 2-CTA pair-UMMA 256x256 (weight TMA-multicast across the + // pair, much higher per-SM MMA throughput than 1-CTA 128x256). + // Each cluster spans 2 SMs: require clusters*2 >= target_sm. + // Needs m%256, n%256, k%64. + const int clusters_2cta = ((m + 255) / 256) * ((n + 255) / 256); + if (m % 256 == 0 && n % 256 == 0 && k % 64 == 0 && + clusters_2cta * 2 >= target_sm) { + // 256x128 frees a deeper (8- vs 6-stage) pipeline; pays only + // when 256x256 is lightly oversubscribed (<= ~2 waves). + const bool square_like = + (n % 128 == 0) && (clusters_2cta <= 2 * target_sm); + return square_like ? 1 : 0; + } + // N-tile ladder: 128x128 when 128x256 underfills; 128x64 only on a + // <=1-wave fit, since halving N doubles M*K panel reloads (costly + // on DRAM-bound mid-M). + int pick = 2; + if (tiles(128, 256) < target_sm && (n % 128 == 0)) { + pick = 3; + if (tiles(128, 64) <= target_sm && (n % 64 == 0)) { + pick = 4; + } + } + return pick; + } + return 5; // SwapAB +} + +// group_masked: tiles scale with num_experts; mm is max_m_per_expert. +inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, + int sm_count) { + if (mm >= 4096) { + return 4; + } + if (mm >= 128) { + // Masked pads every expert to max_m_per_expert, so tiles = + // num_experts * ceil(max_m/tm) * ceil(n/tn). M stays 128. + const int target_sm = ResolveSmCount(sm_count); + auto tiles = [&](int tm, int tn) { + return num_experts * ((mm + tm - 1) / tm) * ((n + tn - 1) / tn); + }; + const int clusters_2cta = + num_experts * ((mm + 255) / 256) * ((n + 255) / 256); + if (mm % 256 == 0 && n % 256 == 0 && k % 64 == 0 && + clusters_2cta * 2 >= target_sm) { + const bool square_like = + (n % 128 == 0) && (clusters_2cta <= 2 * target_sm); + return square_like ? 5 : 4; + } + // N-tile ladder: keep 128x256 (best B-reuse) unless it underfills + // the grid; a blanket 128x128 preference regresses oversubscribed + // mid-M. + int pick = 0; + if (tiles(128, 256) < target_sm && (n % 128 == 0)) { + pick = 2; + // 128x64 only on a <=1-wave fit: halving N doubles M*K panel + // reloads (costly on DRAM-bound mid-M). + if (tiles(128, 64) <= target_sm && (n % 64 == 0)) { + pick = 3; + } + } + return pick; + } + return 1; // SwapAB +} + +// batch: pure alignment ladder (no runtime SM reasoning). +inline int SelectBF16BatchCfg(int m_per_item, int n, int k) { + if (m_per_item % 256 == 0 && n % 256 == 0) { + return 0; + } + if (m_per_item % 128 == 0 && n % 256 == 0) { + return 1; + } + if (m_per_item % 64 == 0 && n % 128 == 0) { + return 2; + } + return -1; +} + +template +constexpr std::array MakeBF16DescTable( + std::index_sequence) { + return {{MakeBF16Desc>()...}}; +} + +constexpr auto kBF16ContiguousCfgs = MakeBF16DescTable( + std::make_index_sequence{}); +constexpr auto kBF16MaskedCfgs = MakeBF16DescTable( + std::make_index_sequence{}); +constexpr auto kBF16BatchCfgs = MakeBF16DescTable( + std::make_index_sequence{}); + +// Divisibility validation for a selected grouped/batch cfg, with the same +// per-rung contract the .cu ladders enforced (N relaxes to %32 for +// non-power-of-2 widths, %64 for predicated tails). +inline void CheckBF16CfgShape(const char* what, const BF16CfgDesc& d, int m, + int n, int k) { + const int n_mod = d.ntail ? 64 : (((d.bn & (d.bn - 1)) != 0) ? 32 : d.bn); + // SwapAB: KBlockM tiles the weight (output N), KBlockN the activation + // (output M). + const int m_div = d.swap ? d.bn : d.bm; + const int n_div = d.swap ? d.bm : n_mod; + TORCH_CHECK(m % m_div == 0, what, " requires M to be divisible by ", m_div, + ", got ", m); + TORCH_CHECK(n % n_div == 0, what, " requires N to be divisible by ", n_div, + ", got ", n); + TORCH_CHECK(k % d.bk == 0, what, " requires K to be divisible by ", d.bk, + ", got ", k); +} + +// Generic id->tile dispatcher for the small catalogs above. +template +void DispatchBF16SmallCfg(int cfg, const char* what, LaunchTile&& launch) { + const bool found = [&](std::integer_sequence) { + return ((cfg == Is ? (launch.template + operator()>(), + true) + : false) || + ...); + }(std::make_integer_sequence{}); + TORCH_CHECK(found, "unknown ", what, " cfg id ", cfg); +} + +// Launch dispatch: maps a catalog id to the tile instantiation. One branch +// per catalog entry, generated from the tuple (gemm_tile.cuh's DispatchCfgAt +// lives in an anonymous namespace, so this is a local twin). +template +void DispatchBF16Cfg(int cfg, LaunchTile&& launch) { + const bool found = [&](std::integer_sequence) { + return ((cfg == Is + ? (launch.template + operator()>(), + true) + : false) || + ...); + }(std::make_integer_sequence{}); + TORCH_CHECK(found, "unknown bf16 cfg id ", cfg); +} + +} // namespace bf16_dispatch +} // namespace halops diff --git a/csrc/kernel/gemm/dense_gemm.cu b/csrc/kernel/gemm/dense_gemm.cu index 46124ab..674765b 100644 --- a/csrc/kernel/gemm/dense_gemm.cu +++ b/csrc/kernel/gemm/dense_gemm.cu @@ -15,6 +15,7 @@ #include #include +#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -31,9 +32,10 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, const std::optional situ_linear_beta) { const CudaDeviceGuard device_guard(input.device()); TORCH_CHECK( - mode == "w8a8-mxfp8" || mode == "w4a4-mxfp4" || mode == "w4a4-nvfp4", + mode == "bf16" || mode == "w8a8-mxfp8" || mode == "w4a4-mxfp4" || + mode == "w4a4-nvfp4", "Unsupported mode: ", mode, - ". Expected 'w8a8-mxfp8', 'w4a4-mxfp4' or 'w4a4-nvfp4'."); + ". Expected 'bf16', 'w8a8-mxfp8', 'w4a4-mxfp4' or 'w4a4-nvfp4'."); TORCH_CHECK(input.dim() == 2, "input must be a 2D tensor of shape [M, K]"); TORCH_CHECK(weight.dim() == 2, "weight must be a 2D tensor of shape [N, K]"); @@ -70,7 +72,211 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, ? static_cast(1.0 / *situ_linear_beta) : 0.0f}; - if (mode == "w8a8-mxfp8") { + if (mode == "bf16") { + // Native BF16: sfa/sfb/bias/alpha are ignored. + using TypeA = cutlass::bfloat16_t; + using TypeB = cutlass::bfloat16_t; + using TypeC = cutlass::bfloat16_t; + using TypeD = cutlass::bfloat16_t; + // Placeholder, never dereferenced. + using TypeSF = cutlass::float_ue8m0_t; + using TypeAccumulate = float; + + TORCH_CHECK(input.dtype() == torch::kBFloat16, + "bf16 dense GEMM: input must be bfloat16"); + TORCH_CHECK(weight.dtype() == torch::kBFloat16, + "bf16 dense GEMM: weight must be bfloat16"); + TORCH_CHECK(output.dtype() == torch::kBFloat16, + "bf16 dense GEMM: output must be bfloat16"); + TORCH_CHECK(epilogue == EpilogueOp::Identity && !output_sf.has_value(), + "bf16 dense GEMM supports EpilogueOp.Identity only"); + + const int k = weight.size(1); + TORCH_CHECK(input.size(1) == k, + "input K must match weight K, got input K=", input.size(1), + ", weight K=", k); + params.k = k; + params.ptr_a = input.data_ptr(); + params.ptr_b = weight.data_ptr(); + params.ptr_sfa = nullptr; + params.ptr_sfb = nullptr; + params.ptr_c = nullptr; + params.ptr_alpha = nullptr; + + // Debug only: HALOPS_FORCE_CFG=256x128x64_2CTA (any name in kKnown, + // i.e. GemmKernelConfigBF16NaiveNoBias) skips the dispatch below + // and runs that config on every shape it supports; other shapes are + // dispatched normally. + static const std::string forced_cfg = [] { + const char* e = std::getenv("HALOPS_FORCE_CFG"); + std::string name(e == nullptr ? "" : e); + static const char* kKnown[] = { + "", + "256x256x64_2CTA", + "256x256x64_2CTA_P7", + "256x128x64_2CTA", + "256x128x64_2CTA_Ntail", + "256x128x64_2CTA_P9", + "256x128x64_2CTA_P9_Ntail", + "256x192x64_2CTA", + "256x64x64_2CTA", + "128x256x64_1CTA", + "128x128x64_1CTA", + "128x64x64_1CTA", + "128x32x64_1CTA", + "128x64x64_2CTA_P18", + "64x224x64_1CTA_P6", + "64x128x64_1CTA", + "64x96x64_1CTA_P11", + "64x64x64_1CTA", + "64x64x64_1WG_1CTA", + "64x64x64_P12_1CTA", + "64x64x64_P14_1CTA", + "64x32x64_1WG_P14_1CTA", + "64x32x64_1WG_P18_1CTA", + "64x64x64_1WG_P14_1CTA", + }; + bool known = false; + for (const char* k : kKnown) { + known = known || name == k; + } + TORCH_CHECK(known, "HALOPS_FORCE_CFG=", name, + " is not a config name this hatch knows; see the " + "kKnown list in dense_gemm.cu."); + return name; + }(); + if (!forced_cfg.empty()) { + // Required n alignment: 32 for non-power-of-2 KBlockN, 64 for + // _Ntail configs, KBlockN otherwise. +#define HALOPS_FORCE_TRY(NAME, CFG, EXTRA) \ + if (forced_cfg == NAME) { \ + using KernelConfig = CFG; \ + constexpr int kNMod = \ + KernelConfig::KForceEpiNPredicate \ + ? 64 \ + : ((KernelConfig::KBlockN & (KernelConfig::KBlockN - 1)) != 0 \ + ? 32 \ + : KernelConfig::KBlockN); \ + constexpr int kNModCluster = kNMod * KernelConfig::KClusterN; \ + if (m % KernelConfig::KBlockM == 0 && n % kNModCluster == 0 && \ + k % KernelConfig::KBlockK == 0 && (EXTRA)) { \ + gemm_impl(params, sm, stream); \ + return; \ + } \ + } + HALOPS_FORCE_TRY("256x256x64_2CTA", + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA, + true) + HALOPS_FORCE_TRY("256x256x64_2CTA_P7", + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA_P7, + true) + HALOPS_FORCE_TRY("256x128x64_2CTA", + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA, + true) + HALOPS_FORCE_TRY( + "256x128x64_2CTA_Ntail", + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail, true) + HALOPS_FORCE_TRY("256x128x64_2CTA_P9", + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9, + true) + HALOPS_FORCE_TRY( + "256x128x64_2CTA_P9_Ntail", + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail, true) + HALOPS_FORCE_TRY("256x192x64_2CTA", + GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA, + true) + HALOPS_FORCE_TRY("256x64x64_2CTA", + GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA, + true) + HALOPS_FORCE_TRY("128x256x64_1CTA", + GemmKernelConfigBF16NaiveNoBias128x256x64_1CTA, + true) + HALOPS_FORCE_TRY("128x128x64_1CTA", + GemmKernelConfigBF16NaiveNoBias128x128x64_1CTA, + true) + HALOPS_FORCE_TRY("128x64x64_1CTA", + GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA, + true) + HALOPS_FORCE_TRY("128x32x64_1CTA", + GemmKernelConfigBF16NaiveNoBias128x32x64_1CTA, + true) + // Only within the correct CTA band. + HALOPS_FORCE_TRY("128x64x64_2CTA_P18", + GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18, + bf16_dispatch::PairDeepCtaCount(m, n) >= + bf16_dispatch::kPairDeepMinCtas && + bf16_dispatch::PairDeepCtaCount(m, n) <= + bf16_dispatch::kPairDeepMaxCtas) + HALOPS_FORCE_TRY("64x224x64_1CTA_P6", + GemmKernelConfigBF16NaiveNoBias64x224x64_1CTA_P6, + true) + HALOPS_FORCE_TRY("64x128x64_1CTA", + GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA, + true) + HALOPS_FORCE_TRY("64x96x64_1CTA_P11", + GemmKernelConfigBF16NaiveNoBias64x96x64_1CTA_P11, + true) + HALOPS_FORCE_TRY("64x64x64_1CTA", + GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA, true) + HALOPS_FORCE_TRY("64x64x64_1WG_1CTA", + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA, + true) + HALOPS_FORCE_TRY("64x64x64_P12_1CTA", + GemmKernelConfigBF16NaiveNoBias64x64x64_P12_1CTA, + true) + HALOPS_FORCE_TRY("64x64x64_P14_1CTA", + GemmKernelConfigBF16NaiveNoBias64x64x64_P14_1CTA, + true) + HALOPS_FORCE_TRY( + "64x32x64_1WG_P14_1CTA", + GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P14_1CTA, true) + HALOPS_FORCE_TRY( + "64x32x64_1WG_P18_1CTA", + GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA, true) + HALOPS_FORCE_TRY( + "64x64x64_1WG_P14_1CTA", + GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA, true) +#undef HALOPS_FORCE_TRY + } + + // Entry guards per tier (same messages the per-rung checks used). + if (m >= 128 && m < 4096) { + CheckDivisible(m, 128, "BF16 GEMM mid M M"); + CheckDivisible(n, 32, "BF16 GEMM mid M N"); + CheckDivisible(k, 64, "BF16 GEMM mid M K"); + } else if (m < 128 && !bf16_dispatch::ThinMNoSwapOk(m, n, k, sm)) { + CheckDivisible(n, 128, "BF16 GEMM SwapAB N"); + CheckDivisible(m, 64, "BF16 GEMM SwapAB M"); + CheckDivisible(k, 64, "BF16 GEMM SwapAB K"); + } + const int cfg = bf16_dispatch::dense::SelectBF16Cfg(m, n, k, sm); + TORCH_CHECK(cfg >= 0, "No BF16 dense GEMM tile supports M=", m, + ", N=", n, ", K=", k); + const auto& desc = bf16_dispatch::kBF16Cfgs[cfg]; + // Same divisibility contract the per-rung checks enforced: the + // output M/N tile multiples (N may relax to %32 for non-power-of-2 + // widths or %64 for predicated-tail tiles), K a KBlockK multiple. + // SwapAB swaps the roles: KBlockM tiles the weight (output N) and + // KBlockN the activation (output M). + const int n_mod = + desc.ntail ? 64 : (((desc.bn & (desc.bn - 1)) != 0) ? 32 : desc.bn); + const int m_div = desc.swap ? desc.bn : desc.bm; + const int n_div = desc.swap ? desc.bm : n_mod; + TORCH_CHECK(m % m_div == 0, + "BF16 dense GEMM requires M to be divisible by ", m_div, + ", got ", m); + TORCH_CHECK(n % n_div == 0, + "BF16 dense GEMM requires N to be divisible by ", n_div, + ", got ", n); + TORCH_CHECK(k % desc.bk == 0, + "BF16 dense GEMM requires K to be divisible by ", desc.bk, + ", got ", k); + bf16_dispatch::DispatchBF16Cfg(cfg, [&]() { + gemm_impl(params, sm, stream); + }); + } else if (mode == "w8a8-mxfp8") { const int k = weight.size(1); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index 125d837..2032ac8 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -52,6 +52,11 @@ class CollectiveEpilogue { using CopyOpT2R = typename KernelTraits::CopyOpT2R; using CopyOpT2R_Sub = typename KernelTraits::CopyOpT2R_Sub; using OverlapComputeTile = typename KernelTraits::OverlapComputeTile; + // Used by the BF16 epilogue path. + using CopyOpT2R_Overlap = typename KernelTraits::CopyOpT2R_Overlap; + using OverlapLoadTile = typename KernelTraits::OverlapLoadTile; + static constexpr uint32_t EpiMIter = + cute::size<0>(EpilogueTile{}) / cute::size<0>(EpiComputeTile{}); // Bias uses plain TMA (no 2SM multicast); each CTA loads its own copy. using CopyOpG2S_Bias = cute::SM90_TMA_LOAD; using CopyOpS2R = @@ -92,6 +97,10 @@ class CollectiveEpilogue { int rows_per_batch = 0; SituCoef situ{}; int64_t gate_ld = 0; + // Tail-only stream-K: fp32 partial workspace, laid out as + // [slot][CtaShape_M][KBlockN] (slot = scheduler.partial_slot()) + // nullptr when stream-K is off. + TypeAccumulate* ptr_partial = nullptr; }; struct Params { @@ -108,6 +117,7 @@ class CollectiveEpilogue { TypeC const* ptr_c = nullptr; int64_t d_ld; int64_t gate_ld; + TypeAccumulate* ptr_partial = nullptr; }; static Params to_underlying_arguments(Arguments const& args) { @@ -154,7 +164,8 @@ class CollectiveEpilogue { args.situ, args.ptr_c, d_ld, - args.gate_ld}; + args.gate_ld, + args.ptr_partial}; } // Producer warp: TMA-loads one bias C stage per scheduled tile. @@ -710,14 +721,558 @@ class CollectiveEpilogue { } } - template + + // BF16 path: TMEM -> registers -> cast -> GMEM through CuTe tiled copies, + // which follow the 16dp (64-row CTA) and 2SM "2x2" accumulator layouts. + // KStreamK: tail-only stream-K instantiation. Compile-time so the + // data-parallel store path keeps its register allocation (a runtime branch + // here causes heavy spills). + template + CUTLASS_DEVICE void epilogue_bf16(Params const& epilogue_params, + AccumulatorPipeline& acc_pipeline, + SharedStorage& shared_storage, + TmemStorage& tmem_storage, int warp_idx, + TileScheduler& scheduler) { + int warp_group_idx = warp_idx / 4; + int block_rank_in_cluster = cute::block_rank_in_cluster(); + + cute::Layout cluster_layout_vmnk = + cute::tiled_divide(cute::make_layout(ClusterShape_MNK{}), + cute::make_tile(typename TiledMma::AtomThrID{})); + auto cta_coord_vmnk = + cluster_layout_vmnk.get_flat_coord(block_rank_in_cluster); + int cta_v = cute::get<0>(cta_coord_vmnk); + + cute::Tensor tmem_accumulators = tmem_storage.tmem_accumulators; + cute::Tensor acc = tmem_accumulators(cute::make_coord(cute::_, cute::_), + cute::_0{}, cute::_0{}, cute::_); + + // TMEM is read in 16-column sub-tiles; KOverlapSubCount of them at the + // stage boundary form the overlap region. + static constexpr int SubTilesPerWG = KernelTraits::KSubTilesPerWG; + static constexpr int OverlapSubCount = KernelTraits::KOverlapSubCount; + + cute::Tensor acc_sub_tile = + cute::flat_divide(acc, OverlapComputeTile{}); + + cute::TiledCopy tiled_t2r_sub = cute::make_tmem_copy( + CopyOpT2R_Sub{}, + acc_sub_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, cute::_0{})); + auto tx = threadIdx.x % cute::size(tiled_t2r_sub); + cute::ThrCopy thread_t2r_sub = tiled_t2r_sub.get_slice(tx); + + cute::Tensor thr_tacc_src_sub = + thread_t2r_sub.partition_S(acc_sub_tile); + cute::Tensor thr_demo_sub = thread_t2r_sub.partition_D( + acc_sub_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, cute::_0{})); + cute::Tensor thr_racc_dst_sub = + cute::make_tensor(cute::shape(thr_demo_sub)); + cute::Tensor thr_rd_sub = + cute::make_tensor(cute::shape(thr_demo_sub)); + + // Unswapped output dims. D rows are d_ld apart: N, or B * N for Batch, + // whose D is [M, B * N] with batch b in columns [b * N, (b + 1) * N). + const size_t out_m = epilogue_params.m; // activation M + const size_t out_n = epilogue_params.n; // weight N + const int64_t d_ld = epilogue_params.d_ld; + + cute::Tensor mD = [&]() { + if constexpr (SwapAB) { + auto stride_d = + cute::make_stride(cute::Int<1>{}, d_ld, out_m * out_n); + auto layout_d = + cute::make_layout(cute::make_shape(out_n, out_m, 1), + cute::append<3>(stride_d, cute::_0{})); + return cute::make_tensor( + cute::make_gmem_ptr(epilogue_params.ptr_d), layout_d); + } else { + auto stride_d = + cute::make_stride(d_ld, cute::_1{}, out_m * out_n); + auto layout_d = + cute::make_layout(cute::make_shape(out_m, out_n, 1), + cute::append<3>(stride_d, cute::_0{})); + return cute::make_tensor( + cute::make_gmem_ptr(epilogue_params.ptr_d), layout_d); + } + }(); + + cute::Tensor gD = cute::local_tile( + mD, cute::take<0, 2>(CtaShape_MNK{}), + cute::make_coord(cute::_, cute::_, cute::Int<0>{})); + + cute::Tensor gD_sub_tile = cute::flat_divide(gD, OverlapComputeTile{}); + auto tiled_r2g_sub = [&]() { + if constexpr (SwapAB) { + return cute::make_tiled_copy_D( + cute::Copy_Atom, TypeD>{}, + tiled_t2r_sub); + } else { + return cute::make_tiled_copy_D( + cute::Copy_Atom{}, + tiled_t2r_sub); + } + }(); + auto thr_r2g_sub = tiled_r2g_sub.get_slice(tx); + cute::Tensor src_sub = thr_r2g_sub.retile_S(thr_rd_sub); + cute::Tensor dst_sub = thr_r2g_sub.partition_D(gD_sub_tile); + + // Coordinates partitioned like dst: the stores below are not clipped, + // so the M bound is checked per element. + auto dst_coords_sub = [&]() { + auto mD_coords = cute::make_identity_tensor( + SwapAB ? cute::make_shape(out_n, out_m, 1) + : cute::make_shape(out_m, out_n, 1)); + auto gD_coords = cute::local_tile( + mD_coords, cute::take<0, 2>(CtaShape_MNK{}), + cute::make_coord(cute::_, cute::_, cute::Int<0>{})); + auto gD_sub_tile_coords = + cute::flat_divide(gD_coords, OverlapComputeTile{}); + return thr_r2g_sub.partition_D(gD_sub_tile_coords); + }(); + + // Tail-only stream-K: partials address a compact per-CTA + // [CtaShape_M][KBlockN] fp32 slot instead of the global D grid. + static constexpr int KPartialM = + cute::size<0>(cute::take<0, 2>(CtaShape_MNK{})); + static constexpr int KPartialN = + cute::size<1>(cute::take<0, 2>(CtaShape_MNK{})); + + // Loop-invariant partial-store partition, built once against the + // workspace base rather than in r2g_sub (inlined per sub-tile; doing it + // there causes spills). Per work item only a pointer offset changes. + // Same thread layout as the D store -> vectorized fp32 stores. Empty + // tuple when !KStreamK so data-parallel codegen is untouched. + auto partial_store = [&]() { + if constexpr (KStreamK) { + auto tiled_p = cute::make_tiled_copy_D( + cute::Copy_Atom< + cute::AutoVectorizingCopyWithAssumedAlignment<128>, + TypeAccumulate>{}, + tiled_t2r_sub); + auto thr_p = tiled_p.get_slice(tx); + return cute::make_tuple( + tiled_p, thr_p.retile_S(thr_racc_dst_sub), + thr_p.partition_D(cute::flat_divide( + cute::make_tensor( + cute::make_gmem_ptr(epilogue_params.ptr_partial), + cute::make_layout( + cute::make_shape(cute::Int{}, + cute::Int{}), + cute::make_stride(cute::Int{}, + cute::_1{}))), + OverlapComputeTile{}))); + } else { + return cute::make_tuple(); + } + }(); + + AccumulatorPipelineState acc_pipe_consumer_state; + + uint32_t epilogue_stage_idx = 0; + + while (scheduler.is_valid()) { + uint32_t m_idx = scheduler.m_idx(); + uint32_t n_idx = scheduler.n_idx(); + // Resolved once per work item: < 0 means it owns the whole K range + // and stores the final bf16 result. + int partial_slot = -1; + int64_t partial_off = 0; + if constexpr (KStreamK) { + partial_slot = scheduler.partial_slot(); + partial_off = + (static_cast(partial_slot) * KNumCTA + cta_v) * + KPartialM * KPartialN; + } + // Batch: move the stacked row b * M + r to row r, columns b * N. + int64_t row_shift = 0; + if constexpr (KernelTraits::KernelType == KernelMode::Batch) { + const int64_t b = scheduler.expert_idx(); + row_shift = b * static_cast(out_n) - + b * scheduler.max_m_per_expert() * d_ld; + } + float alpha_val = 1.0f; + if constexpr (HasAlpha) { + alpha_val = shared_storage.alpha[scheduler.expert_idx()]; + } + acc_pipeline.consumer_wait(acc_pipe_consumer_state); + epilogue_stage_idx = acc_pipe_consumer_state.index(); + + auto t2r_sub = [&](uint32_t epi_m_idx, uint32_t sub_n_idx) { + cute::copy( + tiled_t2r_sub, + thr_tacc_src_sub(cute::_, cute::_, cute::_, epi_m_idx, + sub_n_idx, epilogue_stage_idx), + thr_racc_dst_sub); + if constexpr (!KernelTraits::SkipTmemFence) { + cutlass::arch::fence_view_async_tmem_load(); + } + }; + + auto r2g_sub = [&](uint32_t epi_m_idx, uint32_t sub_n_idx) { + // N-overhang predicate: a KBlockN that does not divide n + // overhangs on the last tile. D is stored register -> GMEM + // (SM100_STORE_256bit, not TMA; CopyOpS2G is unused), so + // nothing clips OOB writes. The host enforces n % KSubTileN == + // 0, so each sub-tile is entirely in or out of bounds: one + // scalar compare, vector store intact. + if constexpr (KernelTraits::KEpiNeedsNPredicate) { + const uint32_t sub_n_begin = + n_idx * static_cast(KernelTraits::KBlockN) + + sub_n_idx * + static_cast(KernelTraits::KSubTileN); + if (sub_n_begin >= static_cast(out_n)) { + return; + } + } + // Stream-K tail chunk (K-slice only): store the raw fp32 + // accumulator to its workspace slot; the reduce kernel sums and + // casts. No alpha: stream-K is gated to no-alpha BF16 dense. + if constexpr (KStreamK) { + if (partial_slot >= 0) { + auto dst_p = cute::get<2>(partial_store); + dst_p.data() = dst_p.data() + partial_off; + copy(cute::get<0>(partial_store), + cute::get<1>(partial_store), + dst_p((cute::_, cute::_), cute::_, cute::_, + cute::Int<0>{}, sub_n_idx)); + return; + } + } + + const uint32_t block_m_idx = m_idx * KNumCTA + cta_v; + auto dst_cur = cute::make_tensor(dst_sub.data() + row_shift, + dst_sub.layout())( + (cute::_, cute::_), cute::_, cute::_, cute::Int<0>{}, + sub_n_idx, block_m_idx, n_idx); + auto coord_cur = dst_coords_sub((cute::_, cute::_), cute::_, + cute::_, cute::Int<0>{}, + sub_n_idx, block_m_idx, n_idx); + + { + constexpr int kN = decltype(cute::size(thr_rd_sub))::value; + using Converter = + cutlass::NumericArrayConverter; + auto& src_arr = + reinterpret_cast&>( + *thr_racc_dst_sub.data()); + auto& dst_arr = + reinterpret_cast&>( + *thr_rd_sub.data()); + if constexpr (HasAlpha) { + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < kN; ++i) { + src_arr[i] *= alpha_val; + } + } + dst_arr = Converter::convert(src_arr); + } + + if constexpr (SwapAB) { + auto store_one = [&](uint32_t v_id) { + auto* addr = (TypeD*)&dst_cur(v_id); + auto val = src_sub[v_id]; + asm volatile("st.global.L1::no_allocate.b16 [%0], %1;" + : + : "l"(addr), "h"(*(uint16_t*)&val)); + }; + if (out_m % KernelTraits::KBlockN == 0) { + // Full M tiles: no bounds check needed. + CUTLASS_PRAGMA_UNROLL + for (uint32_t v_id = 0; v_id < src_sub.size(); ++v_id) { + store_one(v_id); + } + } else { + // Partial last M tile: skip rows past M. + CUTLASS_PRAGMA_UNROLL + for (uint32_t v_id = 0; v_id < src_sub.size(); ++v_id) { + if ((size_t)cute::get<1>(coord_cur(v_id)) >= + out_m) { + continue; + } + store_one(v_id); + } + } + } else { + if (out_m % KernelTraits::KBlockM == 0) { + // Full M tiles: no bounds check needed. + cute::copy(tiled_r2g_sub, src_sub, dst_cur); + } else { + // Predicate per store vector (one vector spans one M + // row), which keeps the 256-bit store. + auto pred_cur = + cute::make_tensor(cute::shape(src_sub)); + CUTLASS_PRAGMA_UNROLL + for (uint32_t v_id = 0; v_id < src_sub.size(); ++v_id) { + pred_cur(v_id) = + (size_t)cute::get<0>(coord_cur(v_id)) < out_m; + } + cute::copy_if(tiled_r2g_sub, pred_cur, src_sub, + dst_cur); + } + } + }; + + auto process_sub = [&](uint32_t epi_m_idx, uint32_t sub_n_idx) { + if constexpr (KernelTraits::IsSfbUnaligned) { + // The last N tile overhangs N; a sub-tile is all in or all + // out because N is a multiple of the sub-tile width. + if (n_idx * cute::size<1>(TileShape{}) + + sub_n_idx * KernelTraits::KSubTileN >= + out_n) { + return; + } + } + t2r_sub(epi_m_idx, sub_n_idx); + r2g_sub(epi_m_idx, sub_n_idx); + }; + + if constexpr (KernelTraits::KTmemOverlapCols > 0) { + // Overlap WG alternates: wg1 on even stages, wg0 on odd. + uint32_t overlap_wg = 1 - (epilogue_stage_idx % 2); + + uint32_t ovlp_sub_base = + (epilogue_stage_idx % 2 == 0) + ? (2 * SubTilesPerWG - OverlapSubCount) + : 0; + + uint32_t wg_sub_base = warp_group_idx * SubTilesPerWG; + + auto overlap_barrier_arrive = [&]() { + constexpr int overlap_bar_threads = 4 * 32 + 32; + if constexpr (KNumCTA == 1) { + cutlass::arch::NamedBarrier::arrive(overlap_bar_threads, + 0); + } else { + if (cta_v == 0) { + cutlass::arch::NamedBarrier::arrive( + overlap_bar_threads, 0); + } else { + constexpr int wg_threads = 4 * 32; + cutlass::arch::NamedBarrier wg_barrier( + wg_threads, 1 /*barrier id*/); + wg_barrier.arrive_and_wait(); + if (threadIdx.x == warp_group_idx * 128) { + // The pair's MMA leader: V is the low bits of + // the cluster rank. + cutlass::arch::ClusterBarrier::arrive( + &shared_storage.overlap_cluster_bar, + cute::block_rank_in_cluster() - cta_v, + true /*pred*/); + } + } + } + }; + + // Remaining (non-overlap) sub-tiles of the overlap WG. + auto process_non_overlap_subs = [&]() { + CUTLASS_PRAGMA_UNROLL + for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; + epi_m_idx++) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t s = 0; s < SubTilesPerWG; s++) { + uint32_t sub_idx = wg_sub_base + s; + if (sub_idx < ovlp_sub_base || + sub_idx >= ovlp_sub_base + OverlapSubCount) { + process_sub(epi_m_idx, sub_idx); + } + } + } + }; + + if constexpr (KernelTraits::KOverlapSingleLoad) { + // Overlap region fits one TMEM load: T2R, arrive, then + // R2G, so MMA resumes without waiting for the stores. + cute::Tensor acc_ovlp_tile = + cute::flat_divide(acc, OverlapLoadTile{}); + cute::TiledCopy tiled_t2r_ovlp = cute::make_tmem_copy( + CopyOpT2R_Overlap{}, + acc_ovlp_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, + cute::_0{})); + auto tx_ovlp = threadIdx.x % cute::size(tiled_t2r_ovlp); + cute::ThrCopy thread_t2r_ovlp = + tiled_t2r_ovlp.get_slice(tx_ovlp); + + cute::Tensor thr_tacc_src_ovlp = + thread_t2r_ovlp.partition_S(acc_ovlp_tile); + cute::Tensor thr_demo_ovlp = thread_t2r_ovlp.partition_D( + acc_ovlp_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, + cute::_0{})); + cute::Tensor thr_racc_dst_ovlp = + cute::make_tensor( + cute::shape(thr_demo_ovlp)); + cute::Tensor thr_rd_ovlp = + cute::make_tensor(cute::shape(thr_demo_ovlp)); + + cute::Tensor gD_ovlp_tile = + cute::flat_divide(gD, OverlapLoadTile{}); + auto tiled_r2g_ovlp = [&]() { + if constexpr (SwapAB) { + return cute::make_tiled_copy_D( + cute::Copy_Atom, + TypeD>{}, + tiled_t2r_ovlp); + } else { + return cute::make_tiled_copy_D( + cute::Copy_Atom< + cute::SM100_STORE_256bit_CACHE_NOALLOCATION, + TypeD>{}, + tiled_t2r_ovlp); + } + }(); + auto thr_r2g_ovlp = tiled_r2g_ovlp.get_slice(tx_ovlp); + cute::Tensor src_ovlp = thr_r2g_ovlp.retile_S(thr_rd_ovlp); + cute::Tensor dst_ovlp = + thr_r2g_ovlp.partition_D(gD_ovlp_tile); + + static constexpr int WideTilesTotal = + KernelTraits::KWideTilesTotal; + uint32_t ovlp_wide_idx = (epilogue_stage_idx % 2 == 0) + ? (WideTilesTotal - 1) + : 0; + + if (warp_group_idx == overlap_wg) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; + epi_m_idx++) { + cute::copy(tiled_t2r_ovlp, + thr_tacc_src_ovlp( + cute::_, cute::_, cute::_, epi_m_idx, + ovlp_wide_idx, epilogue_stage_idx), + thr_racc_dst_ovlp); + cutlass::arch::fence_view_async_tmem_load(); + } + } + + // Overlap columns read; MMA may proceed. + if (warp_group_idx == overlap_wg) { + overlap_barrier_arrive(); + } + + if (warp_group_idx == overlap_wg) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; + epi_m_idx++) { + { + constexpr int kN = + decltype(cute::size(thr_rd_ovlp))::value; + using Converter = + cutlass::NumericArrayConverter< + TypeD, TypeAccumulate, kN>; + auto& src_arr = reinterpret_cast< + cutlass::Array const&>( + *thr_racc_dst_ovlp.data()); + auto& dst_arr = reinterpret_cast< + cutlass::Array&>( + *thr_rd_ovlp.data()); + if constexpr (HasAlpha) { + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < kN; ++i) { + src_arr[i] *= alpha_val; + } + } + dst_arr = Converter::convert(src_arr); + } + + const uint32_t block_m_idx = + m_idx * KNumCTA + cta_v; + auto dst_cur = cute::make_tensor( + dst_ovlp.data() + row_shift, + dst_ovlp.layout())((cute::_, cute::_), cute::_, + cute::_, cute::Int<0>{}, + ovlp_wide_idx, block_m_idx, + n_idx); + + if constexpr (SwapAB) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t v_id = 0; v_id < src_ovlp.size(); + ++v_id) { + auto* addr = (TypeD*)&dst_cur(v_id); + auto val = src_ovlp[v_id]; + asm volatile( + "st.global.L1::no_allocate.b16 " + "[%0], %1;" + : + : "l"(addr), "h"(*(uint16_t*)&val)); + } + } else { + cute::copy(tiled_r2g_ovlp, src_ovlp, dst_cur); + } + } + + process_non_overlap_subs(); + } + } else { + // No single TMEM load covers the overlap region: do + // T2R + R2G per sub-tile, then arrive after the last read. + if (warp_group_idx == overlap_wg) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; + epi_m_idx++) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t o = 0; o < OverlapSubCount; o++) { + process_sub(epi_m_idx, ovlp_sub_base + o); + } + } + } + + if (warp_group_idx == overlap_wg) { + overlap_barrier_arrive(); + } + + if (warp_group_idx == overlap_wg) { + process_non_overlap_subs(); + } + } + + if (warp_group_idx != overlap_wg) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; + epi_m_idx++) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t s = 0; s < SubTilesPerWG; s++) { + process_sub(epi_m_idx, wg_sub_base + s); + } + } + } + } else { + CUTLASS_PRAGMA_UNROLL + for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; + epi_m_idx++) { + uint32_t wg_sub_base = warp_group_idx * SubTilesPerWG; + CUTLASS_PRAGMA_UNROLL + for (uint32_t s = 0; s < SubTilesPerWG; s++) { + process_sub(epi_m_idx, wg_sub_base + s); + } + } + } + + if constexpr (KernelTraits::SkipTmemFence) { + // One fence after the last TMEM load, before releasing the + // stage (instead of one per load). + cutlass::arch::fence_view_async_tmem_load(); + } + acc_pipeline.consumer_release(acc_pipe_consumer_state); + ++acc_pipe_consumer_state; + + scheduler.advance(); + } + } + + // KStreamK: tail-only stream-K instantiation (BF16 only). + template CUTLASS_DEVICE void epilogue(Params const& epilogue_params, AccumulatorPipeline& acc_pipeline, BiasPipeline& bias_pipeline, SharedStorage& shared_storage, TmemStorage& tmem_storage, int warp_idx, TileScheduler& scheduler) { - if constexpr (KernelTraits::KSwapStaged) { + if constexpr (KernelTraits::KIsBF16) { + epilogue_bf16(epilogue_params, acc_pipeline, + shared_storage, tmem_storage, warp_idx, + scheduler); + } else if constexpr (KernelTraits::KSwapStaged) { epilogue_swap(epilogue_params, acc_pipeline, shared_storage, tmem_storage, warp_idx, scheduler); } else { diff --git a/csrc/kernel/gemm/gemm_kernel.cuh b/csrc/kernel/gemm/gemm_kernel.cuh index a30584a..dff7499 100644 --- a/csrc/kernel/gemm/gemm_kernel.cuh +++ b/csrc/kernel/gemm/gemm_kernel.cuh @@ -21,12 +21,14 @@ #include "kernel/gemm/epilogue.cuh" #include "kernel/gemm/gemm_utils.h" #include "kernel/gemm/mainloop_fwd.cuh" +#include "kernel/gemm/stream_k_reduce.cuh" #include "kernel/gemm/tile_scheduler.cuh" namespace halops { template + typename EpilogueParams, typename SchedulerParams, + bool KStreamK = false> __global__ void __launch_bounds__(KernelTraits::KThreads, 1) gemm_kernel(CUTE_GRID_CONSTANT const MainloopParams mainloop_params, CUTE_GRID_CONSTANT const EpilogueParams epilogue_params, @@ -83,21 +85,26 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) bool is_load_ab_warp = (warp_idx == KernelTraits::KLoadABWarpId); + // Prefetch TMA descriptors: AB warp handles A, B (+ SFA, SFB for + // block-scaled modes). BF16 has no scale-factor descriptors. if (is_load_ab_warp && lane_predicate) { cute::prefetch_tma_descriptor( mainloop_params.tma_load_A.get_tma_descriptor()); cute::prefetch_tma_descriptor( mainloop_params.tma_load_B.get_tma_descriptor()); - cute::prefetch_tma_descriptor( - mainloop_params.tma_load_SFA.get_tma_descriptor()); - if constexpr (KernelTraits::IsSfbUnaligned) { - cute::prefetch_tma_descriptor(&mainloop_params.sfb_run_desc); - if constexpr (KernelTraits::KActRowTma) { - cute::prefetch_tma_descriptor(&mainloop_params.act_row_desc); - } - } else { + if constexpr (!KernelTraits::KIsBF16) { cute::prefetch_tma_descriptor( - mainloop_params.tma_load_SFB.get_tma_descriptor()); + mainloop_params.tma_load_SFA.get_tma_descriptor()); + if constexpr (KernelTraits::IsSfbUnaligned) { + cute::prefetch_tma_descriptor(&mainloop_params.sfb_run_desc); + if constexpr (KernelTraits::KActRowTma) { + cute::prefetch_tma_descriptor( + &mainloop_params.act_row_desc); + } + } else { + cute::prefetch_tma_descriptor( + mainloop_params.tma_load_SFB.get_tma_descriptor()); + } } } if constexpr (KernelTraits::AddBias) { @@ -192,9 +199,13 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) BiasPipeline bias_pipeline(shared_storage.bias_pipeline, bias_pipeline_params); + // TMEM allocation, issued right before the barrier that waits on it + // (hoisting it earlier hides nothing). TmemAllocator tmem_allocator{}; if (warp_idx == KernelTraits::KMmaWarpId) { - tmem_allocator.allocate(TmemAllocator::Sm100TmemCapacityColumns, + // Right-sized (KTmemColumns, see kernel_traits.cuh), not the full 512 + // columns; shrinks the TMEM footprint, MMA geometry unchanged. + tmem_allocator.allocate(KernelTraits::KTmemColumns, &shared_storage.tmem_base_ptr); } @@ -219,11 +230,17 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) } TmemStorage tmem_storage = main_loop.init_tmem_tensors(); - main_loop.set_tmem_offsets(tmem_storage, shared_storage.tmem_base_ptr); + // The load warp never touches TMEM, so it skips set_tmem_offsets and with + // it the first tmem_base_ptr read (where tcgen05.alloc latency surfaces), + // reaching its first TMA issue earlier. + if (!is_load_ab_warp) { + main_loop.set_tmem_offsets(tmem_storage, shared_storage.tmem_base_ptr); + } if (is_load_ab_warp) { - // Non-epilogue warps hand registers to the epilogue warps. - if constexpr (KEpilogueWarpGroupCount != 1) { + // Prologue warps need few registers — release to pool for epilogue + // warps. + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } main_loop.tma_loadAB(mainloop_params, mainloop_pipeline, shared_storage, @@ -231,40 +248,48 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) if constexpr (KernelTraits::KUsePdl) { pdl_trigger(); } - } else if (warp_idx == KernelTraits::KMmaWarpId && is_mma_leader_cta) { - if constexpr (KEpilogueWarpGroupCount != 1) { + } else if (warp_idx == KernelTraits::KMmaWarpId && + is_mma_leader_cta) { // mma + // MMA warp uses TMEM for accumulators, needs few GP registers. + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } - main_loop.mma(mainloop_params, mainloop_pipeline, accumulator_pipeline, - shared_storage, tmem_storage, tiled_mma, scheduler); + main_loop.template mma( + mainloop_params, mainloop_pipeline, accumulator_pipeline, + shared_storage, tmem_storage, tiled_mma, scheduler); // 224-column SFB rewriter, in every CTA. } else if (KernelTraits::IsSfbRowShift && warp_idx >= KernelTraits::KSfbTransposeWarpId) { - if constexpr (KEpilogueWarpGroupCount != 1) { + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } + // Guarded so the rewriter (which static_asserts IsSfbRowShift) is not + // instantiated by every other config. if constexpr (KernelTraits::IsSfbRowShift) { main_loop.sfb_shift_rows( mainloop_params, shared_storage, scheduler, warp_idx - KernelTraits::KSfbTransposeWarpId); } } else if (warp_idx <= KernelTraits::KEpilogueWarpEndId) { - if constexpr (KEpilogueWarpGroupCount != 1) { + // Epilogue warps need the most registers for TMEM->reg->smem + // conversion. + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_alloc< KernelTraits::KNumRegsEpilogue>(); } - epilogue_loop.epilogue(epilogue_params, accumulator_pipeline, - bias_pipeline, shared_storage, tmem_storage, - warp_idx, scheduler); + epilogue_loop.template epilogue( + epilogue_params, accumulator_pipeline, bias_pipeline, + shared_storage, tmem_storage, warp_idx, scheduler); } else if (KernelTraits::AddBias && warp_idx == KernelTraits::KLoadCWarpId) { - if constexpr (KEpilogueWarpGroupCount != 1) { + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } epilogue_loop.load_c(epilogue_params, bias_pipeline, shared_storage, scheduler); } else { - if constexpr (KEpilogueWarpGroupCount != 1) { + // Any non-participant warp releases registers. + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } } @@ -277,10 +302,11 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) __syncthreads(); } + // Then deallocate TMEM (must match the allocated column count). if (warp_idx == KernelTraits::KMmaWarpId) { tmem_allocator.release_allocation_lock(); tmem_allocator.free(shared_storage.tmem_base_ptr, - TmemAllocator::Sm100TmemCapacityColumns); + KernelTraits::KTmemColumns); } } @@ -303,10 +329,12 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, "gemm_impl requires ptr_b to be non-null"); TORCH_CHECK(params.ptr_d != nullptr, "gemm_impl requires ptr_d to be non-null"); - TORCH_CHECK(params.ptr_sfa != nullptr, - "gemm_impl requires ptr_sfa to be non-null"); - TORCH_CHECK(params.ptr_sfb != nullptr, - "gemm_impl requires ptr_sfb to be non-null"); + if constexpr (!KernelTraits::KIsBF16) { + TORCH_CHECK(params.ptr_sfa != nullptr, + "gemm_impl requires ptr_sfa to be non-null"); + TORCH_CHECK(params.ptr_sfb != nullptr, + "gemm_impl requires ptr_sfb to be non-null"); + } if constexpr (KernelTraits::AddBias) { TORCH_CHECK( params.ptr_c != nullptr, @@ -423,10 +451,21 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, "gemm_impl requires M to be divisible by KBlockM=", KernelTraits::KBlockM, ", got ", params.m); if constexpr (KernelTraits::IsSfbUnaligned) { + // Unpacked 224-pair tiles load a run of whole 128-row SF + // atoms, which requires n to tile cleanly at 128. TORCH_CHECK(params.n % 128 == 0 && params.n >= 384, "gemm_impl requires N to be a multiple of 128 and " ">= 384 for KBlockN=", KernelTraits::KBlockN, ", got ", params.n); + } else if constexpr (KernelTraits::KEpiNeedsNPredicate) { + // Non-power-of-2 KBlockN (96/112/224) need not divide n; the + // epilogue predicates the overhang per KSubTileN sub-tile. + TORCH_CHECK(params.n % KernelTraits::KSubTileN == 0, + "gemm_impl with KBlockN=", KernelTraits::KBlockN, + " predicates the N overhang per ", + KernelTraits::KSubTileN, + "-wide sub-tile, so N must be divisible by ", + KernelTraits::KSubTileN, ", got ", params.n); } else { TORCH_CHECK(params.n % KernelTraits::KBlockN == 0, "gemm_impl requires N to be divisible by KBlockN=", @@ -445,15 +484,15 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, } } +// Kernel pointer in, not a traits type: the caller picks between the +// data-parallel and the stream-K instantiation of gemm_kernel. template -void LaunchGemmKernel(dim3 dim_grid, dim3 dim_cluster, dim3 dim_block, - int smem_size, cudaStream_t stream, +void LaunchGemmKernel(void const* kernel_ptr, dim3 dim_grid, dim3 dim_cluster, + dim3 dim_block, int smem_size, cudaStream_t stream, const MainloopParams& mainloop_params, const EpilogueParams& epilogue_params, const SchedulerParams& scheduler_params) { - auto* kernel_ptr = &gemm_kernel; CUTE_CHECK_ERROR(cudaFuncSetAttribute( kernel_ptr, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); @@ -463,9 +502,8 @@ void LaunchGemmKernel(dim3 dim_grid, dim3 dim_cluster, dim3 dim_block, const_cast(reinterpret_cast(&scheduler_params)), }; cutlass::Status status = cutlass::ClusterLauncher::launch( - dim_grid, dim_cluster, dim_block, smem_size, stream, - reinterpret_cast(kernel_ptr), kernel_params, - KernelTraits::KUsePdl); + dim_grid, dim_cluster, dim_block, smem_size, stream, kernel_ptr, + kernel_params, KernelTraits::KUsePdl); TORCH_CHECK(status == cutlass::Status::kSuccess, "failed to launch the gemm kernel"); } @@ -485,8 +523,10 @@ void gemm_impl_body(GemmParams& params, const int sm_count, using ClusterShape_MNK = typename KernelTraits::ClusterShape_MNK; static constexpr int KCTAsPerCluster = cute::size(ClusterShape_MNK{}); - const int raw_sm_count = sm_count > 0 ? sm_count : GetSmCount(); - // Only launch full clusters. + // Same SM-count resolution as the dispatch-site tile heuristics. + const int raw_sm_count = ResolveSmCount(sm_count); + // Round down to a multiple of KCTAsPerCluster so every cluster is fully + // occupied. const int runtime_sm_count = (raw_sm_count / KCTAsPerCluster) * KCTAsPerCluster; int M = params.m; @@ -522,7 +562,9 @@ void gemm_impl_body(GemmParams& params, const int sm_count, cute::Layout layout_C = cute::make_layout( cute::make_shape(M, N), cute::make_stride(N, cute::Int<1>{})); - // meet the cutlass's 128 row SfAtoms layout. + // The scale tensors always cover whole 128-row SfAtom atoms even when the + // activation is only M rows. (BF16 passes null SF pointers; these layouts + // are then unused bookkeeping.) const int M_sf = AlignSfM(M); typename KernelTraits::LayoutSFA layout_SFA = SwapAB ? KernelTraits::Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA( @@ -548,6 +590,32 @@ void gemm_impl_body(GemmParams& params, const int sm_count, layout_A, layout_B, layout_SFA, layout_SFB, params.k, params.m, num_experts}); + int scheduler_m = SwapAB ? N : M; + int scheduler_n = SwapAB ? M : N; + // The scheduler sizes the stream-K tail against the persistent grid. + const int num_clusters_planned = runtime_sm_count / KCTAsPerCluster; + const int k_tiles_planned = + cutlass::ceil_div(K, cute::size<2>(typename KernelTraits::TileShape{})); + SchedulerParams scheduler_params = Scheduler::to_underlying_arguments( + scheduler_m, scheduler_n, params.num_experts, params.max_m_per_expert, + params.masked_m, params.expert_ids, num_clusters_planned, + k_tiles_planned); + + // Tail-only stream-K fp32 workspace, allocated only if the scheduler split + // a tail: rem * splits * KNumCTA per-CTA slots of CtaShape_M x KBlockN. + static constexpr int KPartM = KernelTraits::KBlockM / KernelTraits::KNumCTA; + static constexpr int KPartN = KernelTraits::KBlockN; + at::Tensor streamk_ws; + const bool streamk_active = scheduler_params.streamk_rem > 0; + if (streamk_active) { + const int64_t slots = + static_cast(scheduler_params.streamk_rem) * + scheduler_params.streamk_splits * KernelTraits::KNumCTA; + streamk_ws = at::empty( + {slots, static_cast(KPartM), static_cast(KPartN)}, + at::TensorOptions().dtype(at::kFloat).device(at::kCUDA)); + } + EpilogueParams epilogue_params = CollectiveEpilogue::to_underlying_arguments( {static_cast(params.ptr_c), @@ -558,14 +626,11 @@ void gemm_impl_body(GemmParams& params, const int sm_count, KernelTraits::KernelType == KernelMode::Batch ? params.max_m_per_expert : params.m, - params.situ, params.gate_ld}); - - int scheduler_m = SwapAB ? N : M; - int scheduler_n = SwapAB ? M : N; - SchedulerParams scheduler_params = Scheduler::to_underlying_arguments( - scheduler_m, scheduler_n, params.num_experts, params.max_m_per_expert, - params.masked_m, params.expert_ids); + params.situ, params.gate_ld, + streamk_active ? streamk_ws.data_ptr() : nullptr}); + // The launch reserves the whole SMEM capacity, which also keeps multiple + // concurrent streams from fitting two blocks on one SM. static_assert(sizeof(typename KernelTraits::SharedStorage) <= cutlass::arch::sm100_smem_capacity_bytes, "SMEM usage exceeded capacity"); @@ -575,6 +640,21 @@ void gemm_impl_body(GemmParams& params, const int sm_count, int smem_size = cutlass::arch::sm100_smem_capacity_bytes; + // Two instantiations, picked by pointer: data-parallel (unchanged codegen, + // used whenever nothing is split) and fused stream-K. The `if constexpr` + // keeps traits without KSupportsStreamK (all but BF16 dense no-bias + // no-alpha) from instantiating a dead stream-K copy. + auto* kernel_ptr_dp = &gemm_kernel; + void const* kernel_ptr = (void const*)kernel_ptr_dp; + if constexpr (KernelTraits::KSupportsStreamK) { + if (streamk_active) { + kernel_ptr = (void const*)&gemm_kernel; + } + } + dim3 dimBlock(KernelTraits::KThreads); auto cluster_shape = ClusterShape_MNK{}; dim3 dimCluster(cute::size<0>(cluster_shape), cute::size<1>(cluster_shape), @@ -583,13 +663,29 @@ void gemm_impl_body(GemmParams& params, const int sm_count, int num_clusters = runtime_sm_count / KCTAsPerCluster; dim3 dimGrid(dimCluster.x, num_clusters * dimCluster.y); - LaunchGemmKernel(dimGrid, dimCluster, dimBlock, smem_size, - stream, mainloop_params, epilogue_params, - scheduler_params); + LaunchGemmKernel(kernel_ptr, dimGrid, dimCluster, dimBlock, + smem_size, stream, mainloop_params, + epilogue_params, scheduler_params); cudaError_t cuda_status = cudaGetLastError(); if (cuda_status != cudaSuccess) { TORCH_CHECK(false, "CUDA error: ", cudaGetErrorString(cuda_status)); } + + if (streamk_active) { + // Reduce tail fp32 partials into D (whole tiles were already stored + // to D by the main launch). + launch_stream_k_reduce( + static_cast(params.ptr_d), streamk_ws.data_ptr(), + scheduler_params.streamk_tail_base, scheduler_params.streamk_rem, + scheduler_params.streamk_splits, scheduler_params.expert_ctm, + scheduler_params.expert_ctn, scheduler_params.traverse_m_fast, + scheduler_n, stream); + cuda_status = cudaGetLastError(); + if (cuda_status != cudaSuccess) { + TORCH_CHECK(false, "CUDA error (stream-K reduce): ", + cudaGetErrorString(cuda_status)); + } + } } template 1. +// OVLP KTmemOverlapCols. +// REG KNumRegsEpilogue; 160 is the Reg160 occupancy variant. +// SWZ UseTileSwizzle. +// FENCE SkipTmemFence. +// SWAP, FP4 SwapAB, KIsFP4. +// SFVS KSfVecSize: 16 = NVFP4, 32 = MXFP4. +// ALPHA, BIAS HasAlpha, AddBias. +// MODE KernelType. +// OP KEpiOp (epilogue op). +// EWGO KEpilogueWarpGroupsOverride; 0 = auto (SwapAB ? 1 : 2). +// NTAIL KForceEpiNPredicate (predicated store on power-of-2 N). +// BF16 KIsBF16 (native BF16 GEMM, no scale factors). +// ATOM CTAs per MMA atom: 0 = auto (CM*CN > 1 ? 2 : 1), 1 = 1SM, +// 2 = 2x1SM. Decoupled from the cluster shape so a 1SM atom +// can still sit in a multi-CTA cluster and share loads. +// --------------------------------------------------------------------------- template + EpilogueOp OP = EpilogueOp::Identity, int EWGO = 0, + bool NTAIL = false, bool BF16 = false, int ATOM = 0> struct GemmTile : GemmKernelConfig { static constexpr int KBlockM = BM; static constexpr int KBlockN = BN; @@ -50,7 +74,12 @@ struct GemmTile : GemmKernelConfig { static constexpr bool HasAlpha = ALPHA; static constexpr bool AddBias = BIAS; static constexpr KernelMode KernelType = MODE; - static constexpr bool IsPairUmma = (CM * CN) > 1; + // CTAs per MMA atom (0 = legacy: any cluster > 1 implies pair-UMMA). + static constexpr int KAtomCtas = ATOM == 0 ? ((CM * CN) > 1 ? 2 : 1) : ATOM; + static constexpr bool IsPairUmma = KAtomCtas == 2; + static constexpr int KEpilogueWarpGroupsOverride = EWGO; + static constexpr bool KForceEpiNPredicate = NTAIL; + static constexpr bool KIsBF16 = BF16; static constexpr EpilogueOp KEpiOp = OP; static constexpr bool KSwapSfbRun = SWAP; }; @@ -429,4 +458,215 @@ struct CandidateTiles { static constexpr const auto& tiles = kW4a8Tiles; }; +// =========================================================================== +// BF16 (kind::f16) configs — no block-scale, no alpha. KBlockK=64 gives the +// same per-stage A/B smem as FP8@KBlockK=128 and there is no SFA/SFB smem, so +// stage counts can mirror the FP8 configs (< 228 KB). The tail three template +// parameters are BF16-relevant: EWGO (KEpilogueWarpGroupsOverride, 1 for the +// 2SM "2x2" TMEM layout and narrow tiles), NTAIL (KForceEpiNPredicate, the +// predicated store for N % KBlockN != 0), BF16 (KIsBF16). +// --------------------------------------------------------------------------- +// Dense (Naive) +using GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA = + GemmTile<256, 256, 64, 6, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x256x64_1CTA = + GemmTile<128, 256, 64, 4, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x128x64_1CTA = + GemmTile<128, 128, 64, 4, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x32x64_1CTA = + GemmTile<128, 32, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA = + GemmTile<128, 64, 64, 8, 2, 2, 2, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P16 = + GemmTile<128, 64, 64, 16, 2, 2, 2, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18 = + GemmTile<128, 64, 64, 18, 2, 2, 2, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18 = + GemmTile<128, 64, 64, 18, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x96x64_1CTA_P11 = + GemmTile<64, 96, 64, 11, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x224x64_1CTA_P6 = + GemmTile<64, 224, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x64_2x1CTA = + GemmTile<128, 64, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA = + GemmTile<64, 64, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA = + GemmTile<64, 128, 64, 8, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P14_1CTA = + GemmTile<64, 32, 64, 14, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA = + GemmTile<64, 32, 64, 18, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_1CTA = + GemmTile<64, 32, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA = + GemmTile<64, 64, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x64x64_P12_1CTA = + GemmTile<64, 64, 64, 12, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x64x64_P14_1CTA = + GemmTile<64, 64, 64, 14, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA = + GemmTile<64, 64, 64, 14, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x32x64_P4_1CTA = + GemmTile<128, 32, 64, 4, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x32x64_P6_1CTA = + GemmTile<128, 32, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x32x32_1CTA = + GemmTile<128, 32, 32, 16, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA = + GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA = + GemmTile<256, 128, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail = + GemmTile<256, 128, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, true, true>; +using GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA = + GemmTile<256, 64, 64, 10, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA_P7 = + GemmTile<256, 256, 64, 7, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9 = + GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail = + GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, true, true>; +using GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA = + GemmTile<256, 192, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x64_SwapAB_1CTA = + GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x32x64_SwapAB_1CTA = + GemmTile<128, 32, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias256x64x64_SwapAB_2CTA = + GemmTile<256, 64, 64, 9, 2, 2, 1, 0, 208, false, false, true, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; +using GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA = + GemmTile<128, 64, 128, 4, 2, 1, 1, 0, 208, false, false, true, false, 16, + false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; + +// Batch +using GemmKernelConfigBF16BatchNoBias256x256x64_2CTA = + GemmTile<256, 256, 64, 6, 2, 2, 1, 16, 208, false, false, false, false, 16, + false, false, KernelMode::Batch, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16BatchNoBias128x256x64_1CTA = + GemmTile<128, 256, 64, 4, 2, 1, 1, 16, 208, false, false, false, false, 16, + false, false, KernelMode::Batch, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16BatchNoBias128x64x64_SwapAB_1CTA = + GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, + false, false, KernelMode::Batch, EpilogueOp::Identity, 0, false, true>; + +// Group contiguous +using GemmKernelConfigBF16ContiguousNoBias256x256x64_2CTA = + GemmTile<256, 256, 64, 7, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16ContiguousNoBias256x128x64_2CTA = + GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16ContiguousNoBias128x256x64_1CTA = + GemmTile<128, 256, 64, 4, 2, 1, 1, 16, 208, false, false, false, false, 16, + false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16ContiguousNoBias128x128x64_1CTA = + GemmTile<128, 128, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16ContiguousNoBias128x64x64_1CTA = + GemmTile<128, 64, 64, 8, 2, 1, 1, 16, 208, false, false, false, false, 16, + false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16ContiguousNoBias128x64x64_SwapAB_1CTA = + GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, + false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; + +// Group masked +using GemmKernelConfigBF16MaskedNoBias128x256x64_1CTA = + GemmTile<128, 256, 64, 4, 2, 1, 1, 16, 208, false, false, false, false, 16, + false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16MaskedNoBias128x64x64_SwapAB_1CTA = + GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, + false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16MaskedNoBias128x128x64_1CTA = + GemmTile<128, 128, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16MaskedNoBias128x64x64_1CTA = + GemmTile<128, 64, 64, 8, 2, 1, 1, 16, 208, false, false, false, false, 16, + false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16MaskedNoBias256x256x64_2CTA = + GemmTile<256, 256, 64, 7, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; + +using GemmKernelConfigBF16MaskedNoBias256x128x64_2CTA = + GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, + false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; + +// Field-lock asserts: guard against positional-argument drift in the +// 21-parameter alias lists above (migration from hand-written structs). +static_assert(GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KBlockM == 256 && + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KBlockN == 256 && + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KBlockK == 64 && + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KPrologueStages == + 6 && + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::IsPairUmma && + GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KIsBF16); +static_assert( + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail::KForceEpiNPredicate && + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail::KPrologueStages == + 8 && + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail::KPrologueStages == + 9 && + GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail:: + KForceEpiNPredicate); +static_assert( + GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18:: + KEpilogueWarpGroupsOverride == 1 && + GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18::KPrologueStages == + 18 && + GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18::KClusterN == 2); +static_assert(GemmKernelConfigBF16NaiveNoBias128x32x32_1CTA::KBlockK == 32 && + GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA::KBlockK == + 128 && + GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA::SwapAB); +static_assert( + GemmKernelConfigBF16ContiguousNoBias128x256x64_1CTA::KTmemOverlapCols == + 16 && + GemmKernelConfigBF16MaskedNoBias256x128x64_2CTA::KPrologueStages == 9 && + GemmKernelConfigBF16BatchNoBias128x64x64_SwapAB_1CTA::SwapAB); + } // namespace halops diff --git a/csrc/kernel/gemm/gemm_utils.h b/csrc/kernel/gemm/gemm_utils.h index 98da2c4..c781209 100644 --- a/csrc/kernel/gemm/gemm_utils.h +++ b/csrc/kernel/gemm/gemm_utils.h @@ -59,4 +59,28 @@ constexpr int AlignSfM(int m) { return (m + kSfAtomM - 1) / kSfAtomM * kSfAtomM; } +inline void CheckDivisible(int64_t value, int64_t divisor, const char* name) { + TORCH_CHECK(value % divisor == 0, name, " must be divisible by ", divisor, + ", got ", value); +} + +// SM count for the tile-selection heuristics. `sm_count <= 0` falls back to +// the cached device count, so dispatch sees the same SM count gemm_impl +// launches onto (a hard-coded value would mis-pick tiles in the +// `tiles(...) < target_sm` ladders). +inline int ResolveSmCount(int sm_count) { + return sm_count > 0 ? sm_count : GetSmCount(); +} + +inline void CheckGemmTileShape(int64_t m, int64_t n, int64_t k, int64_t tile_m, + int64_t tile_n, int64_t tile_k, + const char* kernel_name) { + TORCH_CHECK(m % tile_m == 0, kernel_name, " requires M to be divisible by ", + tile_m, ", got ", m); + TORCH_CHECK(n % tile_n == 0, kernel_name, " requires N to be divisible by ", + tile_n, ", got ", n); + TORCH_CHECK(k % tile_k == 0, kernel_name, " requires K to be divisible by ", + tile_k, ", got ", k); +} + } // namespace halops diff --git a/csrc/kernel/gemm/group_contiguous_gemm.cu b/csrc/kernel/gemm/group_contiguous_gemm.cu index a442bfc..f993138 100644 --- a/csrc/kernel/gemm/group_contiguous_gemm.cu +++ b/csrc/kernel/gemm/group_contiguous_gemm.cu @@ -15,6 +15,7 @@ #include #include +#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -30,10 +31,11 @@ void GroupContiguousGemm(const torch::Tensor& input, const std::string& mode = "w8a8-mxfp8") { const CudaDeviceGuard device_guard(input.device()); TORCH_CHECK( - mode == "w8a8-mxfp8" || mode == "w4a4-nvfp4" || mode == "w4a4-mxfp4" || - mode == "w4a8-mxfp4", + mode == "bf16" || mode == "w8a8-mxfp8" || mode == "w4a4-nvfp4" || + mode == "w4a4-mxfp4" || mode == "w4a8-mxfp4", "Unsupported mode: ", mode, - ". Expected 'w8a8-mxfp8', 'w4a4-nvfp4', 'w4a4-mxfp4' or 'w4a8-mxfp4'."); + ". Expected 'bf16', 'w8a8-mxfp8', 'w4a4-nvfp4', 'w4a4-mxfp4' or " + "'w4a8-mxfp4'."); TORCH_CHECK(input.dim() == 2, "input must be a 2D tensor of shape [M, K]"); TORCH_CHECK(weight.dim() == 3, "weight must be a 3D tensor of shape [num_experts, N, K]"); @@ -63,7 +65,45 @@ void GroupContiguousGemm(const torch::Tensor& input, params.num_experts = num_experts; params.use_pdl = true; - if (mode == "w8a8-mxfp8") { + if (mode == "bf16") { + using TypeA = cutlass::bfloat16_t; + using TypeB = cutlass::bfloat16_t; + using TypeC = cutlass::bfloat16_t; + using TypeD = cutlass::bfloat16_t; + using TypeSF = cutlass::float_ue8m0_t; // placeholder, unused + using TypeAccumulate = float; + + const int k = weight.size(2); + TORCH_CHECK(input.size(1) == k, + "input K must match weight K, got input K=", input.size(1), + ", weight K=", k); + TORCH_CHECK(input.dtype() == torch::kBFloat16, + "bf16 contiguous GEMM: input must be bfloat16"); + TORCH_CHECK(weight.dtype() == torch::kBFloat16, + "bf16 contiguous GEMM: weight must be bfloat16"); + TORCH_CHECK(output.dtype() == torch::kBFloat16, + "bf16 contiguous GEMM: output must be bfloat16"); + params.k = k; + params.ptr_a = input.data_ptr(); + params.ptr_b = weight.data_ptr(); + params.ptr_sfa = nullptr; + params.ptr_sfb = nullptr; + params.ptr_alpha = nullptr; + + const int cfg = bf16_dispatch::SelectBF16ContiguousCfg(m, n, k, sm); + TORCH_CHECK(cfg >= 0, "bf16 contiguous GEMM: unsupported shape M=", m, + " N=", n, " K=", k); + bf16_dispatch::CheckBF16CfgShape( + "bf16 contiguous GEMM", bf16_dispatch::kBF16ContiguousCfgs[cfg], m, + n, k); + bf16_dispatch::DispatchBF16SmallCfg< + bf16_dispatch::BF16ContiguousTiles, + bf16_dispatch::kBF16ContiguousCount>( + cfg, "bf16 contiguous", [&]() { + gemm_impl(params, sm, stream); + }); + } else if (mode == "w8a8-mxfp8") { const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), diff --git a/csrc/kernel/gemm/group_masked_gemm.cu b/csrc/kernel/gemm/group_masked_gemm.cu index e672725..c003f82 100644 --- a/csrc/kernel/gemm/group_masked_gemm.cu +++ b/csrc/kernel/gemm/group_masked_gemm.cu @@ -15,6 +15,7 @@ #include #include +#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -29,10 +30,11 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, const std::string& mode = "w8a8-mxfp8") { const CudaDeviceGuard device_guard(input.device()); TORCH_CHECK( - mode == "w8a8-mxfp8" || mode == "w4a4-nvfp4" || mode == "w4a4-mxfp4" || - mode == "w4a8-mxfp4", + mode == "bf16" || mode == "w8a8-mxfp8" || mode == "w4a4-nvfp4" || + mode == "w4a4-mxfp4" || mode == "w4a8-mxfp4", "Unsupported mode: ", mode, - ". Expected 'w8a8-mxfp8', 'w4a4-nvfp4', 'w4a4-mxfp4' or 'w4a8-mxfp4'."); + ". Expected 'bf16', 'w8a8-mxfp8', 'w4a4-nvfp4', 'w4a4-mxfp4' or " + "'w4a8-mxfp4'."); TORCH_CHECK(input.dim() == 2, "input must be a 2D tensor of shape [num_experts * " "max_m_per_expert, K]"); @@ -72,7 +74,46 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.max_m_per_expert = max_m_per_expert; params.use_pdl = true; - if (mode == "w8a8-mxfp8") { + if (mode == "bf16") { + using TypeA = cutlass::bfloat16_t; + using TypeB = cutlass::bfloat16_t; + using TypeC = cutlass::bfloat16_t; + using TypeD = cutlass::bfloat16_t; + using TypeSF = cutlass::float_ue8m0_t; // placeholder, unused + using TypeAccumulate = float; + + const int k = weight.size(2); + TORCH_CHECK(input.size(1) == k, + "input K must match weight K, got input K=", input.size(1), + ", weight K=", k); + TORCH_CHECK(input.dtype() == torch::kBFloat16, + "bf16 masked GEMM: input must be bfloat16"); + TORCH_CHECK(weight.dtype() == torch::kBFloat16, + "bf16 masked GEMM: weight must be bfloat16"); + TORCH_CHECK(output.dtype() == torch::kBFloat16, + "bf16 masked GEMM: output must be bfloat16"); + params.k = k; + params.ptr_a = input.data_ptr(); + params.ptr_b = weight.data_ptr(); + params.ptr_sfa = nullptr; + params.ptr_sfb = nullptr; + params.ptr_alpha = nullptr; + + const int cfg = bf16_dispatch::SelectBF16MaskedCfg( + num_experts, max_m_per_expert, n, k, sm); + TORCH_CHECK(cfg >= 0, + "bf16 masked GEMM: unsupported shape E=", num_experts, + " max_m_per_expert=", max_m_per_expert, " N=", n, " K=", k); + bf16_dispatch::CheckBF16CfgShape("bf16 masked GEMM", + bf16_dispatch::kBF16MaskedCfgs[cfg], + max_m_per_expert, n, k); + bf16_dispatch::DispatchBF16SmallCfg( + cfg, "bf16 masked", [&]() { + gemm_impl(params, sm, stream); + }); + } else if (mode == "w8a8-mxfp8") { const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), diff --git a/csrc/kernel/gemm/kernel_traits.cuh b/csrc/kernel/gemm/kernel_traits.cuh index 1444d51..a495745 100644 --- a/csrc/kernel/gemm/kernel_traits.cuh +++ b/csrc/kernel/gemm/kernel_traits.cuh @@ -87,17 +87,35 @@ struct GemmKernelTraits { static constexpr int KNumCTA = IsPairUmma ? 2 : 1; static constexpr int KClusterM = KernelConfig_::KClusterM; static constexpr int KClusterN = KernelConfig_::KClusterN; - // KNumCTA 1: cta_group::1 UMMA; 2: pair-UMMA (2x1SM, cta_group::2). - // MMA K step: 64 elements for FP4, 32 for FP8. + // KNumCTA == 1: single-CTA UMMA (SM100_MMA_..._SS, cta_group::1) + // KNumCTA == 2: pair-UMMA (SM100_MMA_..._2x1SM_SS, cta_group::2) + // FP4: MMA K-increment is 64 elements; FP8: MMA K-increment is 32 elements. + // BF16: non-block-scaled kind::f16 MMA, K-increment is 16 elements. static constexpr bool KIsFP4 = KernelConfig_::KIsFP4; - // Narrow the A TMA box to the real M below KBlockM (the UMMA still reads - // KBlockM rows; the epilogue drops D past M). + static constexpr bool KIsBF16 = KernelConfig_::KIsBF16; + // Narrow the A TMA box to the real M below KBlockM (the UMMA + // still reads KBlockM rows and the epilogue drops D past M); static constexpr bool KNarrowA = NarrowA_ && (KDenseW8A8MXFP8 || (KernelType == KernelMode::Batch && !AddBias)) && + !KIsBF16 && !SwapAB && !IsPairUmma && !KernelConfig_::KIsFP4 && KBlockK == 128; static constexpr bool KUsePdl = UsePdl_; - static constexpr int KMmaK = KIsFP4 ? 64 : 32; + static constexpr int KMmaK = KIsFP4 ? 64 : (KIsBF16 ? 16 : 32); + // Tail-only stream-K eligibility; single source of truth for the + // scheduler's split decision and for emitting the KStreamK=true kernel. + // Only the BF16 dense no-bias no-alpha epilogue can deposit a raw fp32 + // partial (the bias epilogue has no stream-K path; the reduce kernel does + // not apply alpha). Also excluded, each a silent wrong-result otherwise: + // * SwapAB: the tail fold-back math assumes non-swap traversal + // (m=64 n=19584 k=1024 gave 121% rel error; HALOPS_STREAMK=0 + // disables stream-K); + // * N-predicated tiles: the compact per-tile fp32 partial slot would + // leave holes that the reduce kernel sums. + static constexpr bool KSupportsStreamK = + KernelType == KernelMode::Dense && KIsBF16 && !AddBias && !HasAlpha && + !SwapAB && (KBlockN % 128 == 0 || KBlockN == 32 || KBlockN == 64) && + !KernelConfig_::KForceEpiNPredicate; static constexpr int kItersK = KBlockK / KMmaK; static constexpr bool KBFp4Unpack = !KIsFP4 && cute::sizeof_bits_v == 4; @@ -122,11 +140,15 @@ struct GemmKernelTraits { static constexpr int KQuantAccCols = KAccColsPerOut * mxfp8::kGroup; // Epilogue warp groups split N: 1 for bf16 SwapAB (small N) and for a // quantized tile narrower than two quant groups, 2 otherwise. + // KEpilogueWarpGroupsOverride can force 1, e.g. to make KBlockN=32 legal + // at CtaM==64 (KEpiComputeN = 32 meets the T2R atom floor). static constexpr int KEpilogueWarpGroupCount = - (SwapAB && !KQuantD) || - (KQuantD && !SwapAB && KBlockN < 2 * KQuantAccCols) - ? 1 - : 2; + KernelConfig_::KEpilogueWarpGroupsOverride != 0 + ? KernelConfig_::KEpilogueWarpGroupsOverride + : (((SwapAB && !KQuantD) || + (KQuantD && !SwapAB && KBlockN < 2 * KQuantAccCols)) + ? 1 + : 2); static constexpr int KEpilogueWarpStartId = 0; static constexpr int KEpilogueWarpEndId = KEpilogueWarpGroupCount * 4 - 1; static constexpr int KLoadABWarpId = KEpilogueWarpEndId + 1; @@ -137,6 +159,13 @@ struct GemmKernelTraits { static constexpr int KNumRegsEpilogue = KernelConfig_::KNumRegsEpilogue; static constexpr bool SkipTmemFence = KernelConfig_::SkipTmemFence; static constexpr int KNumRegsOther = 88; + // Whether to do runtime register redistribution (setmaxnreg): needs enough + // warps for the 208+88 split. Not keyed on the epilogue warp-group count; + // without it ptxas gives every warp one flat budget (54-87 regs, starving + // the epilogue). Quantized configs keep the warp-group-count rule. + static constexpr bool KRedistributeRegs = + KIsBF16 ? (KNumWarp >= 8 && (!SwapAB || KernelType == KernelMode::Dense)) + : KEpilogueWarpGroupCount != 1; using TileShape = cute::Shape, cute::Int, cute::Int>; @@ -148,14 +177,44 @@ struct GemmKernelTraits { static constexpr int KEpiComputeN = KBlockN / KEpilogueWarpGroupCount; using EpiComputeTile = cute::Shape, cute::Int>; - // TMEM is read in 16-wide sub-tiles when overlap is on or the per-WG width - // has no TMEM load atom (e.g. 112); KTmemOverlapCols and KEpiComputeN only - // need to be multiples of 16. + // Sub-tile for overlap TMEM load splitting. + // When overlap is enabled, always use 16-wide sub-tiles (TMEM load atom + // width). This is fully general: KTmemOverlapCols need not divide + // KEpiComputeN evenly, as long as both are multiples of 16. Falls back to + // EpiComputeTile when overlap is disabled (KTmemOverlapCols==0). + // + // Non-power-of-2 KBlockN (e.g. 96/112/224, for one-wave occupancy): the + // T2R tables only have atoms for KEpiComputeN in {16, 32, 64, 128}, so + // such widths are decomposed into uniform KSubTileN=32 sub-tiles (16 would + // give only 8 fp32/thread, too few for SM100_STORE_256bit). Not legal on + // the 2SM "2x2" layout, whose second N half sits on datapaths 64-127: a + // 32-wide slice straddles the half boundary and writes wrong elements. + // A per-warp-group width of 8 (224-pair, KEpiComputeN=112 falls back to + // 32-wide sub-tiles here) has no single atom either. + static constexpr bool KEpiNIsSingleAtom = + (KEpiComputeN == 16 || KEpiComputeN == 32 || KEpiComputeN == 64 || + KEpiComputeN == 128); + // Quantized dtypes keep main's rule: 16-wide unless the per-WG width has + // its own atom (8 included). static constexpr bool KEpiComputeNHasAtom = - KEpiComputeN == 128 || KEpiComputeN == 64 || KEpiComputeN == 32 || - KEpiComputeN == 16 || KEpiComputeN == 8; + KEpiNIsSingleAtom || KEpiComputeN == 8; static constexpr int KSubTileN = - (KTmemOverlapCols == 0 && KEpiComputeNHasAtom) ? KEpiComputeN : 16; + KIsBF16 ? (KTmemOverlapCols != 0 + ? 16 + : (KEpiNIsSingleAtom + ? KEpiComputeN + : (KEpiComputeN % 32 == 0 ? 32 : 16))) + : ((KTmemOverlapCols == 0 && KEpiComputeNHasAtom) ? KEpiComputeN + : 16); + // KIs2SmHalfM spelled out (it is declared further down). + static_assert(!KIsBF16 || KEpiNIsSingleAtom || + !(KNumCTA == 2 && KBlockM == 128), + "a non-power-of-2 KBlockN cannot use the 2SM 128-row \"2x2\" " + "TMEM layout: its N dimension is (KBlockN/2, 2) over two " + "datapath halves, so the 32-wide epilogue sub-tiles straddle " + "the half boundary and the store lands on wrong elements " + "(measured 67.85% mismatch). Use a 1-CTA KBlockM=64 config, " + "whose 16-datapath layout maps N straight to columns."); using OverlapComputeTile = cute::conditional_t< KSubTileN == KEpiComputeN, EpiComputeTile, cute::Shape, cute::Int>>; @@ -169,49 +228,220 @@ struct GemmKernelTraits { (KTmemOverlapCols == 16 || KTmemOverlapCols == 32 || KTmemOverlapCols == 64 || KTmemOverlapCols == 128); - // The op width (`Nx` = columns per datapath) must equal KEpiComputeN: a - // narrower op that fits moves only part of the tile. Widths with no atom - // (e.g. 48) use the 16-wide sub-tile path (CopyOpT2R_Sub). + // ---- TMEM column budget ---------------------------------------------- + // tcgen05.alloc takes a power-of-2 column count in [32, 512]; accumulators + // need KEpilogueStages * KBlockN columns. Right-sizing is perf-neutral but + // gives a truthful footprint for small tiles. BF16 without overlap only: + // block-scaled dtypes also keep SFA/SFB in TMEM, and overlap shares + // columns between stages, so both keep the full 512. + static constexpr int KAccTmemColumns = KEpilogueStages * KBlockN; + static constexpr int round_up_tmem_columns(int v) { + int r = 32; + while (r < v) { + r *= 2; + } + return r > 512 ? 512 : r; + } + static constexpr int KTmemColumns = + (KIsBF16 && KTmemOverlapCols == 0) + ? round_up_tmem_columns(KAccTmemColumns) + : 512; + + // ---- TMEM load (T2R) atom selection: depends on BOTH per-CTA M and N ---- + // `NNdp` is the number of TMEM datapath lanes an atom addresses. A 1SM + // 64-row accumulator only occupies the first 16 lanes of each of the 4 + // subpartitions, so it needs a 16dp atom (32dp fails "Non-injective + // Layout"), with the N repeat count HALVED relative to 32dp. The tiled + // copy stays 128 threads either way. + static constexpr int KEpiCtaM = KBlockM / KNumCTA; + static_assert(KEpiCtaM == 64 || KEpiCtaM == 128, + "UMMA accumulators support 64 or 128 rows per CTA only " + "(mma_traits_sm100.hpp:502)."); + // 16dp32b8x is too narrow for the 256-bit store, so a 64-row CTA tile + // needs KEpiComputeN >= 32. + static_assert(KEpiCtaM == 128 || KEpiComputeN >= 32, + "CtaM==64 needs a 16dp TMEM load atom, whose N repeat count " + "is half the 32dp one; KEpiComputeN < 32 would land on " + "16dp32b8x, which cannot fill SM100_STORE_256bit."); + + // ---- Which TMEM accumulator layout are we actually reading? ------------ + // 1CTA, KBlockM=64 -> 1SM half-subpartition: 16 lanes/subpartition, N + // in TMEM columns (16dp atom). + // 2CTA, KBlockM=128 -> 2SM "2x2": second half of N on datapaths 64-127, + // only N/2 columns used (32dp atom). + // 2CTA, KBlockM=256 -> 2SM "4x1": all 128 lanes, N in columns. + // The "2x2" case needs a 32dp atom AND an epilogue tile spanning the full + // KBlockN (KEpilogueWarpGroupsOverride = 1); otherwise warps 2/3 address + // outside the tile and the output is silently wrong (no assert fires). + static constexpr bool KIs2SmHalfM = (KNumCTA == 2) && (KEpiCtaM == 64); + static constexpr int KEpiTmemDp = + (KNumCTA == 1 && KEpiCtaM == 64) ? 16 : 32; + static_assert(!KIs2SmHalfM || KEpiComputeN == KBlockN, + "2SM accumulators with KBlockM=128 use the 2x2 TMEM layout, " + "whose second N half sits on datapaths 64-127; the epilogue " + "tile must cover the full KBlockN (set " + "KEpilogueWarpGroupsOverride = 1) or warps 2/3 address " + "outside the tile and the output is silently wrong."); + + // CopyOp for loading the full overlap region in one shot (when + // KOverlapSingleLoad). Width-matched to KTmemOverlapCols. Fallback to 16x + // when not single-load. + using CopyOpT2R_Overlap = cute::conditional_t< + KEpiTmemDp == 16, + // 16dp: N repeat halved relative to the 32dp column below. + cute::conditional_t< + KTmemOverlapCols == 16, cute::SM100_TMEM_LOAD_16dp32b8x, + cute::conditional_t< + KTmemOverlapCols == 32, cute::SM100_TMEM_LOAD_16dp32b16x, + cute::conditional_t>>, + cute::conditional_t< + KTmemOverlapCols == 16, cute::SM100_TMEM_LOAD_32dp32b16x, + cute::conditional_t< + KTmemOverlapCols == 32, cute::SM100_TMEM_LOAD_32dp32b32x, + cute::conditional_t>>>; + + static constexpr int KOverlapLoadN = + KOverlapSingleLoad ? KTmemOverlapCols + : (KTmemOverlapCols == 0 ? 16 : KSubTileN); + using OverlapLoadTile = + cute::Shape, cute::Int>; + + static constexpr int KWideTilesTotal = KBlockN / KOverlapLoadN; + + // Select TMEM load op based on EpiComputeTile N dimension (and CtaM). + // The `Nx` suffix is the column count; a mismatched width silently moves + // the wrong columns, so every width a config can ask for needs its own + // arm. The 16dp series (CtaM == 64) uses HALVED atom width (N/2). using CopyOpT2R = cute::conditional_t< - KEpiComputeN == 128, cute::SM100_TMEM_LOAD_32dp32b128x, + KEpiTmemDp == 16, + cute::conditional_t< + KEpiComputeN == 128, cute::SM100_TMEM_LOAD_16dp32b64x, + cute::conditional_t>, cute::conditional_t< - KEpiComputeN == 64, cute::SM100_TMEM_LOAD_32dp32b64x, + KIs2SmHalfM, + // 2SM "2x2": only KEpiComputeN/2 TMEM columns are used, so the + // column repeat is halved relative to the 4x1 case below. + cute::conditional_t< + KEpiComputeN == 128, cute::SM100_TMEM_LOAD_32dp32b64x, + cute::conditional_t>, cute::conditional_t< - KEpiComputeN == 32, cute::SM100_TMEM_LOAD_32dp32b32x, - cute::conditional_t>>>; - // 16x yields 16 bf16 values per thread, exactly one 256-bit store; 8x is - // too narrow for the store atom. - using CopyOpT2R_Sub = + KEpiComputeN == 128, cute::SM100_TMEM_LOAD_32dp32b128x, + cute::conditional_t< + KEpiComputeN == 64, cute::SM100_TMEM_LOAD_32dp32b64x, + cute::conditional_t< + KEpiComputeN == 32, cute::SM100_TMEM_LOAD_32dp32b32x, + cute::conditional_t< + KEpiComputeN == 8, cute::SM100_TMEM_LOAD_32dp32b8x, + cute::SM100_TMEM_LOAD_32dp32b16x>>>>>>; + // Overlap path: 16-wide sub-tile load (16 fp32/thread fills + // SM100_STORE_256bit; 8x is too few). No overlap: width-matched CopyOpT2R. + // CtaM==64 halves the repeat count, as above. + // + // TMEM columns per KSubTileN-wide sub-tile: N/2 on the 16dp and 2SM "2x2" + // layouts (upper N half on other datapaths), N on 4x1. + static constexpr int KSubTileTmemCols = + (KEpiTmemDp == 16 || KIs2SmHalfM) ? KSubTileN / 2 : KSubTileN; + // Width-matched atom for one sub-tile; only for non-power-of-2 KBlockN. + using CopyOpT2R_SubWide = cute::conditional_t< + KEpiTmemDp == 16, + cute::conditional_t< + KSubTileTmemCols == 64, cute::SM100_TMEM_LOAD_16dp32b64x, + cute::conditional_t< + KSubTileTmemCols == 32, cute::SM100_TMEM_LOAD_16dp32b32x, + cute::conditional_t>>, + cute::conditional_t< + KSubTileTmemCols == 128, cute::SM100_TMEM_LOAD_32dp32b128x, + cute::conditional_t< + KSubTileTmemCols == 64, cute::SM100_TMEM_LOAD_32dp32b64x, + cute::conditional_t< + KSubTileTmemCols == 32, cute::SM100_TMEM_LOAD_32dp32b32x, + cute::conditional_t>>>>; + using CopyOpT2R_Sub = cute::conditional_t< + !KIsBF16, cute::conditional_t; + cute::SM100_TMEM_LOAD_32dp32b16x>, + cute::conditional_t< + KTmemOverlapCols == 0, + cute::conditional_t, + cute::conditional_t>>; + + // ---- Close the CopyOpT2R fall-through --------------------------------- + // Each chain above ends in a default (narrowest) atom, which make_tmem_copy + // replicates over the tile. That is only correct when the atom width + // divides the tile; otherwise it compiles clean and writes wrong elements. + static_assert(!KIsBF16 || KEpiComputeN % KSubTileN == 0, + "the epilogue sub-tile loop must cover KEpiComputeN exactly"); + static_assert(!KIsBF16 || KEpiNIsSingleAtom || KTmemOverlapCols != 0 || + KSubTileTmemCols % 16 == 0, + "KEpiComputeN outside {16,32,64,128} falls through to the " + "16-column atom; make_tmem_copy can only replicate that over " + "the tile when the tile's TMEM column count is a multiple of " + "16. Widen the table before using such a width."); + + // Non-power-of-2 KBlockN tiles may overhang N, so the store is predicated + // at KSubTileN granularity (n must be a multiple of it). A config can + // force this for a power-of-2 KBlockN via KForceEpiNPredicate (e.g. + // N=1600 on a 128-wide tile, KSubTileN=64). + static constexpr bool KEpiNeedsNPredicate = + KIsBF16 && (((KBlockN & (KBlockN - 1)) != 0) || + KernelConfig_::KForceEpiNPredicate); // Scale-factor vector size: 16 = NVFP4, 32 = MXFP4. static constexpr int KSFVecSize = KernelConfig_::KSfVecSize; + // Real MMA atom used for the actual A@B computation. + // FP4 -> SM100_MMA_MXF4_SS / _2x1SM_SS (block-scaled, has TypeSF) + // FP8 -> SM100_MMA_MXF8F6F4_SS / _2x1SM_SS (block-scaled, has TypeSF) + // BF16 -> SM100_MMA_F16BF16_SS / _2x1SM_SS (NON block-scaled, no SF) using MMA_T = cute::conditional_t< - KIsFP4, - cute::conditional_t< - KNumCTA == 1, - cute::SM100_MMA_MXF4_SS(TileShape{}), - cute::get<1>(TileShape{}), KSFVecSize, - cute::UMMA::Major::K, cute::UMMA::Major::K>, - cute::SM100_MMA_MXF4_2x1SM_SS< - TypeA_Mma, TypeB_Mma, TypeAccumulate_, TypeSF, - cute::get<0>(TileShape{}), cute::get<1>(TileShape{}), - KSFVecSize, cute::UMMA::Major::K, cute::UMMA::Major::K>>, + KIsBF16, cute::conditional_t< KNumCTA == 1, - cute::SM100_MMA_MXF8F6F4_SS< - TypeA_Mma, TypeB_Mma, TypeAccumulate_, TypeSF, + cute::SM100_MMA_F16BF16_SS< + TypeA_Mma, TypeB_Mma, TypeAccumulate_, cute::get<0>(TileShape{}), cute::get<1>(TileShape{}), cute::UMMA::Major::K, cute::UMMA::Major::K>, - cute::SM100_MMA_MXF8F6F4_2x1SM_SS< - TypeA_Mma, TypeB_Mma, TypeAccumulate_, TypeSF, + cute::SM100_MMA_F16BF16_2x1SM_SS< + TypeA_Mma, TypeB_Mma, TypeAccumulate_, cute::get<0>(TileShape{}), cute::get<1>(TileShape{}), - cute::UMMA::Major::K, cute::UMMA::Major::K>>>; + cute::UMMA::Major::K, cute::UMMA::Major::K>>, + cute::conditional_t< + KIsFP4, + cute::conditional_t< + KNumCTA == 1, + cute::SM100_MMA_MXF4_SS< + TypeA_Mma, TypeB_Mma, TypeAccumulate_, TypeSF, + cute::get<0>(TileShape{}), cute::get<1>(TileShape{}), + KSFVecSize, cute::UMMA::Major::K, cute::UMMA::Major::K>, + cute::SM100_MMA_MXF4_2x1SM_SS< + TypeA_Mma, TypeB_Mma, TypeAccumulate_, TypeSF, + cute::get<0>(TileShape{}), cute::get<1>(TileShape{}), + KSFVecSize, cute::UMMA::Major::K, cute::UMMA::Major::K>>, + cute::conditional_t< + KNumCTA == 1, + cute::SM100_MMA_MXF8F6F4_SS< + TypeA_Mma, TypeB_Mma, TypeAccumulate_, TypeSF, + cute::get<0>(TileShape{}), cute::get<1>(TileShape{}), + cute::UMMA::Major::K, cute::UMMA::Major::K>, + cute::SM100_MMA_MXF8F6F4_2x1SM_SS< + TypeA_Mma, TypeB_Mma, TypeAccumulate_, TypeSF, + cute::get<0>(TileShape{}), cute::get<1>(TileShape{}), + cute::UMMA::Major::K, cute::UMMA::Major::K>>>>; using TiledMma = decltype(cute::make_tiled_mma(MMA_T{})); CUTE_STATIC_ASSERT_V(cute::evenly_divides(TileShape{}, @@ -219,10 +449,44 @@ struct GemmKernelTraits { "Static cluster shape used: TileShape should be " "evenly divided by TiledMma"); - // An unaligned-N tile (see IsSfbUnaligned) reads its scale as a run of - // 128-row atoms, so its SF MMA atom is 128 wide, in the tile's own recipe. + // The F16BF16 atom has NO scale-factor members (SFVecSize, MMA_ScaleFactor, + // FrgTypeSFA/SFB). For BF16 the SF types below are derived from a dummy + // MXF4 MMA so they stay well-formed (never used at runtime; the mainloop + // guards them with if constexpr(!KIsBF16)). MXF4 (SFVecSize=16) rather + // than MXF8F6F4 (32): 64 / 16 = 4 matches the SfAtom's 4-in-K granularity. + // + // The dummy uses a fixed SFTileShape rather than TileShape, so the + // block-scaled constraints (1-CTA M == 128, KBlockK == 64) do not leak + // into BF16 tile choices (e.g. M=64, KBlockK=32). For FP8/FP4 SFTileShape + // IS TileShape and TiledMmaForSF IS TiledMma: codegen unchanged. + static constexpr int KSFDummyM = KNumCTA == 1 ? 128 : 256; + using SFTileShape = cute::conditional_t< + KIsBF16, + cute::Shape, cute::Int<128>, cute::Int<64>>, + TileShape>; + using DummySFMma_T = cute::conditional_t< + KNumCTA == 1, + cute::SM100_MMA_MXF4_SS(SFTileShape{}), + cute::get<1>(SFTileShape{}), 16, + cute::UMMA::Major::K, cute::UMMA::Major::K>, + cute::SM100_MMA_MXF4_2x1SM_SS< + cutlass::float_e2m1_t, cutlass::float_e2m1_t, TypeAccumulate_, + cutlass::float_ue4m3_t, cute::get<0>(SFTileShape{}), + cute::get<1>(SFTileShape{}), 16, cute::UMMA::Major::K, + cute::UMMA::Major::K>>; + using TiledMmaForSF = + cute::conditional_t; + + // For unaligned-N pair tiles (see IsSfbUnaligned) the SFB tile is a run of + // 128-row atoms, so the SF MMA atom is 128 wide rather than round_up(N). + // BF16 never takes this arm (KIsBF16 -> TiledMmaForSF is the dummy, no + // SFB is loaded) and neither does the aligned-N majority. using MMA_SF_T = cute::conditional_t< - SwapAB || KBlockN % 128 == 0, typename TiledMma::MMA_ScaleFactor, + KIsBF16 || SwapAB || KBlockN % 128 == 0, + typename TiledMmaForSF::MMA_ScaleFactor, cute::conditional_t< KIsFP4, cute::SM100_MMA_MXF4_SS>, cute::Tile>; + // SF fragment types for the mainloop's TMEM SF tensors (from TiledMmaForSF, + // since the BF16 TiledMma lacks them). + using FrgTypeSFA = typename TiledMmaForSF::FrgTypeSFA; + using FrgTypeSFB = typename TiledMmaForSF::FrgTypeSFB; + using AtomThrShapeMNK = cute::Shape( typename TiledMma::ThrLayoutVMNK{})), cute::_1, cute::_1>; using CtaShape_MNK = decltype(cute::shape_div(TileShape{}, AtomThrShapeMNK{})); + // Per-CTA SFTileShape; equals CtaShape_MNK for FP8/FP4. + using SFCtaShape_MNK = + decltype(cute::shape_div(SFTileShape{}, AtomThrShapeMNK{})); - static constexpr uint32_t SFVectorSize = TiledMma::SFVecSize; + static constexpr uint32_t SFVectorSize = TiledMmaForSF::SFVecSize; using Sm1xxBlkScaledConfig = cutlass::detail::Sm1xxBlockScaledConfig; using Blk_MN = typename Sm1xxBlkScaledConfig::Blk_MN; static constexpr bool IsCtaNSmall = cute::size<1>(CtaShape_MNK{}) < Blk_MN{}; static constexpr int IsCtaN64 = cute::size<1>(CtaShape_MNK{}) == 64; + // A pair tile whose N is not a multiple of the 128-row SF atom (e.g. 224) + // starts at a 32-row-aligned offset inside an atom. SFB is then loaded as + // the covering run of whole atoms, and the MMA's SFB TMEM address is moved + // forward by the offset (one TMEM column holds 32 rows of an atom). + // BF16 has no scale factors and never takes this path. static constexpr bool IsSfbUnaligned = - !KIsFP4 && (!SwapAB || KernelConfig_::KSwapSfbRun) && KBlockN > 128 && - KBlockN % 128 != 0; + !KIsBF16 && !KIsFP4 && (!SwapAB || KernelConfig_::KSwapSfbRun) && + KBlockN > 128 && KBlockN % 128 != 0; static_assert(!IsSfbUnaligned || KBlockN % 32 == 0, "unaligned SFB tiles need KBlockN % 32 == 0"); // Used when BLOCK_N=224. @@ -273,14 +550,14 @@ struct GemmKernelTraits { static int constexpr CTA_N_SF = IsSfbUnaligned ? KSfbLoadN - : int(cutlass::ceil_div(cute::size<1>(CtaShape_MNK{}), Blk_MN{}) * + : int(cutlass::ceil_div(cute::size<1>(SFCtaShape_MNK{}), Blk_MN{}) * Blk_MN{}); using TileShape_SF = decltype(cute::make_shape( - cute::get<0>(CtaShape_MNK{}), + cute::get<0>(SFCtaShape_MNK{}), cute::Int{} * - cute::shape<2>(typename TiledMma::ThrLayoutVMNK()), - cute::get<2>(TileShape{}))); + cute::shape<2>(typename TiledMmaForSF::ThrLayoutVMNK()), + cute::get<2>(SFTileShape{}))); using MmaShapeA_MK = decltype(cute::partition_shape_A( TiledMma{}, cute::make_shape(cute::size<0>(TileShape{}), cute::size<2>(TileShape{})))); @@ -318,12 +595,20 @@ struct GemmKernelTraits { using LayoutSFB = decltype(Sm1xxBlkScaledConfig::deduce_layoutSFB()); using SmemLayoutAtomSFA = - decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFA(TiledMma{}, - TileShape{})); - using SmemLayoutAtomSFB = + decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFA(TiledMmaForSF{}, + SFTileShape{})); + // Unaligned-N SFB loads a run of KSfbAtoms whole 128-row atoms (see + // IsSfbUnaligned), so the SMEM atom covers CTA_N_SF rows rather than + // SFTileShape's N. For every other tile (incl. the BF16 dummy, whose SF + // layouts are never used at runtime) the SFTileShape form applies. + using SmemLayoutAtomSFB = cute::conditional_t< + IsSfbUnaligned, decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFB( - TiledMma{}, cute::Shape, cute::Int, - cute::Int>{})); + TiledMmaForSF{}, + cute::Shape, cute::Int, + cute::Int>{})), + decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFB(TiledMmaForSF{}, + SFTileShape{}))>; using SmemLayoutSFA = decltype(cute::make_layout( cute::append(cute::shape(SmemLayoutAtomSFA{}), @@ -375,10 +660,11 @@ struct GemmKernelTraits { 128) cute::ArrayEngine> A; alignas( 128) cute::ArrayEngine> B; - alignas( - 128) cute::ArrayEngine> SFA; - alignas( - 128) cute::ArrayEngine> SFB; + // SFA/SFB SMEM: size 0 for BF16 (no scale factors). + alignas(128) cute::ArrayEngine< + TypeSF, KIsBF16 ? 0 : cute::cosize_v> SFA; + alignas(128) cute::ArrayEngine< + TypeSF, KIsBF16 ? 0 : cute::cosize_v> SFB; // Zero-sized unless AddBias. alignas(128) cute::ArrayEngine< TypeC, AddBias ? cute::cosize_v : 0> C; @@ -432,7 +718,8 @@ struct GemmKernelTraits { }; static constexpr bool KActRowTma = - KernelType == KernelMode::Batch && SwapAB && IsPairUmma && !KIsFP4; + KernelType == KernelMode::Batch && SwapAB && IsPairUmma && !KIsFP4 && + !KIsBF16; static constexpr int KActRowAlign = std::gcd(KBlockN, mxfp8::kAtomRows); static constexpr int KCtaRows = KBlockM / KNumCTA; @@ -459,7 +746,7 @@ struct GemmKernelTraits { static constexpr bool KEpiStageFits = KEpiStageOffset + KEpiStageBytes <= cutlass::arch::sm100_smem_capacity_bytes; - static constexpr bool KSwapStaged = SwapAB && KEpiStageFits; + static constexpr bool KSwapStaged = SwapAB && !KIsBF16 && KEpiStageFits; static constexpr int KSmemBytes = KSwapStaged || KQuantD ? KEpiStageOffset + KEpiStageBytes : (int)sizeof(SharedStorage); diff --git a/csrc/kernel/gemm/mainloop_fwd.cuh b/csrc/kernel/gemm/mainloop_fwd.cuh index 5b38d51..9e82b77 100644 --- a/csrc/kernel/gemm/mainloop_fwd.cuh +++ b/csrc/kernel/gemm/mainloop_fwd.cuh @@ -27,6 +27,9 @@ struct CollectiveMainloop { using TiledMma = typename KernelTraits::TiledMma; using TiledMma_SF = typename KernelTraits::TiledMma_SF; + using TiledMmaForSF = typename KernelTraits::TiledMmaForSF; + // BF16 (kind::f16) has no block-scale factors; SF paths compile out. + static constexpr bool KIsBF16 = KernelTraits::KIsBF16; using AtomThrID = typename TiledMma::AtomThrID; using UtccpOp = cute::conditional_t( GmemTiledLoad{}, cute::make_tensor(static_cast(nullptr), LayoutSFA{}), - SmemLayoutSFA{}(cute::_, cute::_, cute::_, cute::Int<0>{}), TileShape{}, - TiledMma{}, ClusterLayout_VMNK{})); + SmemLayoutSFA{}(cute::_, cute::_, cute::_, cute::Int<0>{}), + SFTileShape{}, TiledMmaForSF{}, ClusterLayout_VMNK{})); // Unaligned-N SFB loads through `sfb_run_desc`. struct NoSfbTma {}; @@ -191,9 +197,11 @@ struct CollectiveMainloop { // with 16 transaction bytes, so the barrier's arrival count is unchanged. static constexpr uint32_t KSfbReadyTx = 16; static constexpr uint32_t TmaTransactionBytesAB = - TmaTransactionBytesA + TmaTransactionBytesB + TmaTransactionBytesSFA + - (IsSfbRowShift ? KSfbReadyTx * KernelTraits::KNumCTA - : TmaTransactionBytesSFB); + KIsBF16 ? (TmaTransactionBytesA + TmaTransactionBytesB) + : (TmaTransactionBytesA + TmaTransactionBytesB + + TmaTransactionBytesSFA + + (IsSfbRowShift ? KSfbReadyTx * KernelTraits::KNumCTA + : TmaTransactionBytesSFB)); struct Arguments { TypeA const* ptr_a; @@ -254,10 +262,10 @@ struct CollectiveMainloop { tiled_mma, acc_shape, OverlapTile{}); cute::Tensor tmem_SFA = - cute::make_tensor( + cute::make_tensor( cute::shape(SmemLayoutAtomSFA{})); cute::Tensor tmem_SFB = - cute::make_tensor( + cute::make_tensor( cute::shape(SmemLayoutAtomSFB{})); TmemStorage{}), @@ -318,77 +321,101 @@ struct CollectiveMainloop { SmemLayoutB{}(cute::_, cute::_, cute::_, cute::Int<0>{}), TileShape{}, TiledMma{}, cluster_layout_vmnk); - TMALoad_SFA tma_load_sfa = cute::make_tma_atom_A_sm100( - GmemTiledLoad{}, tensor_sfa, - SmemLayoutSFA{}(cute::_, cute::_, cute::_, cute::Int<0>{}), - TileShape{}, TiledMma{}, cluster_layout_vmnk); + // BF16: SF pointers are null (encoding a TMA atom from them would + // fault on the host), so return default-constructed SF atoms. + if constexpr (KIsBF16) { + return {args.layout_A, + args.layout_B, + args.layout_SFA, + args.layout_SFB, + tma_load_A, + tma_load_B, + TMALoad_SFA{}, + TMALoad_SFB{}, + cute::TmaDescriptor{}, + cute::TmaDescriptor{}, + cute::TmaDescriptor{}, + args.m, + k, + args.num_experts}; + } else { + cute::Tensor tensor_sfa = + cute::make_tensor(args.ptr_sfa, args.layout_SFA); + cute::Tensor tensor_sfb = + cute::make_tensor(args.ptr_sfb, args.layout_SFB); + + TMALoad_SFA tma_load_sfa = cute::make_tma_atom_A_sm100( + GmemTiledLoad{}, tensor_sfa, + SmemLayoutSFA{}(cute::_, cute::_, cute::_, cute::Int<0>{}), + TileShape{}, TiledMmaForSF{}, cluster_layout_vmnk); + + TMALoad_SFB tma_load_sfb{}; + if constexpr (!IsSfbUnaligned) { + tma_load_sfb = cute::make_tma_atom_B_sm100( + GmemTiledLoadSfb{}, tensor_sfb, + SmemLayoutSFB{}(cute::_, cute::_, cute::_, cute::Int<0>{}), + TileShape_SF{}, TiledMma_SF{}, cluster_layout_sfb_vmnk); + } - TMALoad_SFB tma_load_sfb{}; - if constexpr (!IsSfbUnaligned) { - tma_load_sfb = cute::make_tma_atom_B_sm100( - GmemTiledLoadSfb{}, tensor_sfb, - SmemLayoutSFB{}(cute::_, cute::_, cute::_, cute::Int<0>{}), - TileShape_SF{}, TiledMma_SF{}, cluster_layout_sfb_vmnk); - } + const auto row_box_desc = [&](cute::TmaDescriptor& desc, + const void* ptr, auto layout, + int box_rows, const char* what) { + EncodeTmaDesc<2>(&desc, CU_TENSOR_MAP_DATA_TYPE_UINT8, ptr, + {static_cast(k), + static_cast(cute::size<0>(layout))}, + {static_cast(cute::stride<0>(layout))}, + {static_cast(KernelTraits::KBlockK), + static_cast(box_rows)}, + CU_TENSOR_MAP_SWIZZLE_128B, what); + }; + cute::TmaDescriptor a_run_desc{}; + if constexpr (KernelTraits::KNarrowA) { + const int rows = NarrowARows(args.m, args.num_experts); + row_box_desc(a_run_desc, args.ptr_a, args.layout_A, + rows > 0 ? rows + : std::min(cute::size<0>(args.layout_A), + KernelTraits::KBlockM), + "narrow A"); + } + cute::TmaDescriptor act_row_desc{}; + if constexpr (KernelTraits::KActRowTma) { + row_box_desc(act_row_desc, args.ptr_b, args.layout_B, + KernelTraits::KBlockN / KernelTraits::KNumCTA, + "activation rows"); + } + cute::TmaDescriptor sfb_run_desc{}; + if constexpr (IsSfbUnaligned) { + // tile_atom_to_shape_SFB orders atoms K-block first, then N. + const uint64_t k_blks = cute::size<1, 1>(args.layout_SFB); + // Grouped modes lay the experts out after the N atoms, so they fold + // into the same run dimension (one stride per atom). + const uint64_t n_atoms = static_cast( + cute::ceil_div(cute::size<0>(args.layout_B), 128)); + EncodeTmaDesc<3>( + &sfb_run_desc, CU_TENSOR_MAP_DATA_TYPE_UINT16, args.ptr_sfb, + {kSfbAtomBytes / 2, k_blks, + n_atoms * + static_cast(SwapAB ? 1 : args.num_experts)}, + {kSfbAtomBytes, k_blks * kSfbAtomBytes}, + {kSfbAtomBytes / 2, 1, KSfbAtoms}, CU_TENSOR_MAP_SWIZZLE_NONE, + "SFB atom run"); + } - const auto row_box_desc = [&](cute::TmaDescriptor& desc, - const void* ptr, auto layout, - int box_rows, const char* what) { - EncodeTmaDesc<2>(&desc, CU_TENSOR_MAP_DATA_TYPE_UINT8, ptr, - {static_cast(k), - static_cast(cute::size<0>(layout))}, - {static_cast(cute::stride<0>(layout))}, - {static_cast(KernelTraits::KBlockK), - static_cast(box_rows)}, - CU_TENSOR_MAP_SWIZZLE_128B, what); - }; - cute::TmaDescriptor a_run_desc{}; - if constexpr (KernelTraits::KNarrowA) { - const int rows = NarrowARows(args.m, args.num_experts); - row_box_desc(a_run_desc, args.ptr_a, args.layout_A, - rows > 0 ? rows - : std::min(cute::size<0>(args.layout_A), - KernelTraits::KBlockM), - "narrow A"); + return {args.layout_A, + args.layout_B, + args.layout_SFA, + args.layout_SFB, + tma_load_A, + tma_load_B, + tma_load_sfa, + tma_load_sfb, + sfb_run_desc, + a_run_desc, + act_row_desc, + args.m, + k, + args.num_experts}; } - cute::TmaDescriptor act_row_desc{}; - if constexpr (KernelTraits::KActRowTma) { - row_box_desc(act_row_desc, args.ptr_b, args.layout_B, - KernelTraits::KBlockN / KernelTraits::KNumCTA, - "activation rows"); - } - cute::TmaDescriptor sfb_run_desc{}; - if constexpr (IsSfbUnaligned) { - // tile_atom_to_shape_SFB orders atoms K-block first, then N. - const uint64_t k_blks = cute::size<1, 1>(args.layout_SFB); - // Grouped modes lay the experts out after the N atoms, so they fold - // into the same run dimension (one stride per atom). - const uint64_t n_atoms = static_cast( - cute::ceil_div(cute::size<0>(args.layout_B), 128)); - EncodeTmaDesc<3>( - &sfb_run_desc, CU_TENSOR_MAP_DATA_TYPE_UINT16, args.ptr_sfb, - {kSfbAtomBytes / 2, k_blks, - n_atoms * - static_cast(SwapAB ? 1 : args.num_experts)}, - {kSfbAtomBytes, k_blks * kSfbAtomBytes}, - {kSfbAtomBytes / 2, 1, KSfbAtoms}, CU_TENSOR_MAP_SWIZZLE_NONE, - "SFB atom run"); - } - - return {args.layout_A, - args.layout_B, - args.layout_SFA, - args.layout_SFB, - tma_load_A, - tma_load_B, - tma_load_sfa, - tma_load_sfb, - sfb_run_desc, - a_run_desc, - act_row_desc, - args.m, - k, - args.num_experts}; } CUTLASS_DEVICE void tma_loadAB(Params const& mainloop_params, @@ -408,7 +435,8 @@ struct CollectiveMainloop { TileScheduler& scheduler) { bool select_thr = cute::elect_one_sync(); - uint32_t tile_num_k = + // Unused: the per-work-item K range comes from the scheduler. + [[maybe_unused]] uint32_t tile_num_k = cute::ceil_div(mainloop_params.k, cute::size<2>(TileShape{})); int block_rank_in_cluster = cute::block_rank_in_cluster(); @@ -461,7 +489,11 @@ struct CollectiveMainloop { }(); cute::Tensor cta_sA = shared_storage.tensor_sA(); cute::Tensor cta_sB = shared_storage.tensor_sB(); - cute::ThrMMA cta_mma = tiled_mma.get_slice(block_rank_in_cluster); + // Slice by the atom's thread coordinate, not the flat cluster rank: + // with a 1SM atom in a multi-CTA cluster the extra CTAs would index + // past the atom's thread layout and get invalid A/B fragments. + cute::ThrMMA cta_mma = tiled_mma.get_slice( + block_rank_in_cluster % cute::size(typename TiledMma::AtomThrID{})); cute::Tensor gA = cute::local_tile( A, TileShape{}, cute::make_coord(cute::_, cute::_, cute::_), @@ -555,10 +587,17 @@ struct CollectiveMainloop { block_rank_in_cluster % cute::size(typename TiledMma_SF::AtomThrID{})); + // SF tiling must use SFTileShape + TiledMmaForSF consistently: for BF16 + // they are dummy stand-ins (kernel_traits.h) and mixing them with the + // real ones breaks tma_partition's mode-0 sizes, even though no SF + // load is issued. Identical to the real ones for FP8/FP4. + cute::ThrMMA cta_mma_sfa = TiledMmaForSF{}.get_slice( + block_rank_in_cluster % + cute::size(typename TiledMmaForSF::AtomThrID{})); cute::Tensor gSFA = cute::local_tile( - SFA, TileShape{}, cute::make_coord(cute::_, cute::_, cute::_), + SFA, SFTileShape{}, cute::make_coord(cute::_, cute::_, cute::_), cute::Step{}); - cute::Tensor cta_gSFA = cta_mma.partition_A(gSFA); + cute::Tensor cta_gSFA = cta_mma_sfa.partition_A(gSFA); auto [tma_gSFA, tma_sSFA] = cute::tma_partition( mainloop_params.tma_load_SFA, cute::get<2>(cta_coord_vmnk), @@ -668,12 +707,19 @@ struct CollectiveMainloop { lo + KernelTraits::KBlockM - narrow_rows); narrow_smem_row = narrow_row - lo; } - for (uint32_t k_tile_id = 0; k_tile_id < tile_num_k; ++k_tile_id) { + // Stream-K: a work item may cover only a K-slice. Producer and + // mma() consumer both take the range from the scheduler, so stage + // counts always match. + const uint32_t k_lo = scheduler.k_begin(); + const uint32_t k_hi = scheduler.k_end(); + for (uint32_t k_tile_id = k_lo; k_tile_id < k_hi; ++k_tile_id) { ab_pipeline.producer_acquire(mainloop_pipe_producer_state); BarrierType* tma_barrier = ab_pipeline.producer_get_barrier( mainloop_pipe_producer_state); prologue_stage_idx = mainloop_pipe_producer_state.index(); + // Issue A, B (+ SFA, SFB unless BF16) TMA copies on the same + // barrier. if (select_thr) { if constexpr (IsSfbRowShift) { cutlass::arch::ClusterTransactionBarrier:: @@ -718,12 +764,16 @@ struct CollectiveMainloop { tma_sB(cute::_, (cute::Int<0>{}, prologue_stage_idx))); } - cute::copy(mainloop_params.tma_load_SFA.with( - *tma_barrier, mcast_mask_sfa), - a_tile(tma_gSFA, m_idx, k_tile_id, expert_idx), - tma_sSFA(cute::_, - (cute::Int<0>{}, prologue_stage_idx))); - if constexpr (!IsSfbUnaligned) { + if constexpr (!KIsBF16) { + cute::copy(mainloop_params.tma_load_SFA.with( + *tma_barrier, mcast_mask_sfa), + a_tile(tma_gSFA, m_idx, k_tile_id, expert_idx), + tma_sSFA(cute::_, + (cute::Int<0>{}, prologue_stage_idx))); + } + if constexpr (KIsBF16) { + // No scale factors. + } else if constexpr (!IsSfbUnaligned) { cute::copy( mainloop_params.tma_load_SFB.with(*tma_barrier, mcast_mask_sfb), @@ -820,7 +870,7 @@ struct CollectiveMainloop { } } - template + template CUTLASS_DEVICE void mma(Params const& mainloop_params, MainloopPipeline& mainloop_pipeline, AccumulatorPipeline& accumulator_pipeline, @@ -829,13 +879,17 @@ struct CollectiveMainloop { TileScheduler& scheduler) { bool select_thr = cute::elect_one_sync(); - uint32_t tile_num_k = + // Unused: the per-work-item K range comes from the scheduler. + [[maybe_unused]] uint32_t tile_num_k = cute::ceil_div(mainloop_params.k, cute::size<2>(TileShape{})); uint32_t iter_k = KernelTraits::kItersK; int block_rank_in_cluster = cute::block_rank_in_cluster(); + // Same atom-rank rule as tma_loadAB_impl (see there). + int cta_atom_rank = + block_rank_in_cluster % cute::size(typename TiledMma::AtomThrID{}); - cute::ThrMMA cta_mma = tiled_mma.get_slice(block_rank_in_cluster); + cute::ThrMMA cta_mma = tiled_mma.get_slice(cta_atom_rank); uint32_t prologue_stage_idx = 0; uint32_t epilogue_stage_idx = 0; @@ -885,15 +939,24 @@ struct CollectiveMainloop { AccumulatorPipelineState accumulator_pipe_producer_state = cutlass::make_producer_start_state(); - // The next tile's accumulator stage and first k-block are waited on - // right after the current tile's MMAs are issued, before the TMEM - // overlap barrier. - bool next_tile_ready = false; + // KStreamK=false only: the next tile's accumulator stage and first + // k-stage are waited on right after the current tile's MMAs are + // issued, before the TMEM overlap barrier, hiding the producer's + // stage latency. With stream-K the K ranges of consecutive work + // items differ, so the first k-stage of the next item is not the + // next pipeline stage -- the prefetch is skipped and every k-tile + // waits explicitly. + [[maybe_unused]] bool next_tile_ready = false; while (scheduler.is_valid()) { - if (!next_tile_ready) { + if constexpr (KStreamK) { accumulator_pipeline.producer_acquire( accumulator_pipe_producer_state); + } else { + if (!next_tile_ready) { + accumulator_pipeline.producer_acquire( + accumulator_pipe_producer_state); + } } epilogue_stage_idx = accumulator_pipe_producer_state.index(); @@ -925,38 +988,63 @@ struct CollectiveMainloop { }(); tiled_mma.accumulate_ = cute::UMMA::ScaleOut::Zero; - for (uint32_t k_tile_id = 0; k_tile_id < tile_num_k; ++k_tile_id) { + + // Stream-K: same K range the producer used (see tma_loadAB). + const uint32_t k_lo = scheduler.k_begin(); + const uint32_t k_hi = scheduler.k_end(); + for (uint32_t k_tile_id = k_lo; k_tile_id < k_hi; ++k_tile_id) { prologue_stage_idx = mainloop_pipe_consumer_state.index(); - if (k_tile_id != 0 || !next_tile_ready) { + // Data-parallel: the first k-stage of a prefetched tile was + // already waited on below (after the previous tile's MMAs). + if constexpr (KStreamK) { mainloop_pipeline.consumer_wait( mainloop_pipe_consumer_state); + } else { + if (k_tile_id != k_lo || !next_tile_ready) { + mainloop_pipeline.consumer_wait( + mainloop_pipe_consumer_state); + } } - if (select_thr) { - cute::copy( - tiled_copy_s2t_SFA, - thr_sSFA_s2t(cute::_, cute::_, cute::_, cute::_, - prologue_stage_idx), - thr_tSFA_s2t(cute::_, cute::_, cute::_, cute::_)); - cute::copy( - tiled_copy_s2t_SFB, - thr_sSFB_s2t(cute::_, cute::_, cute::_, cute::_, - prologue_stage_idx), - thr_tSFB_s2t_tile(cute::_, cute::_, cute::_, cute::_)); + // UTCCP copy of scale factors into TMEM (block-scaled only). + if constexpr (!KIsBF16) { + if (select_thr) { + copy(tiled_copy_s2t_SFA, + thr_sSFA_s2t(cute::_, cute::_, cute::_, cute::_, + prologue_stage_idx), + thr_tSFA_s2t(cute::_, cute::_, cute::_, cute::_)); + copy(tiled_copy_s2t_SFB, + thr_sSFB_s2t(cute::_, cute::_, cute::_, cute::_, + prologue_stage_idx), + thr_tSFB_s2t_tile(cute::_, cute::_, cute::_, + cute::_)); + } } CUTLASS_PRAGMA_UNROLL for (uint32_t k_block_id = 0; k_block_id < iter_k; ++k_block_id) { - cute::gemm(tiled_mma.with( - tiled_mma.accumulate_, - tmem_SFA(cute::_, cute::_, k_block_id), - tmem_SFB_mma(cute::_, cute::_, k_block_id)), - tile_rA(cute::_, cute::_, k_block_id, - prologue_stage_idx), - tile_rB(cute::_, cute::_, k_block_id, - prologue_stage_idx), - tmem_accumulators(cute::_, cute::_, cute::_, - epilogue_stage_idx)); + if constexpr (KIsBF16) { + // kind::f16 MMA: no scale factors; accumulate flag + // comes from tiled_mma.accumulate_. + gemm(tiled_mma, + tile_rA(cute::_, cute::_, k_block_id, + prologue_stage_idx), + tile_rB(cute::_, cute::_, k_block_id, + prologue_stage_idx), + tmem_accumulators(cute::_, cute::_, cute::_, + epilogue_stage_idx)); + } else { + gemm(tiled_mma.with( + tiled_mma.accumulate_, + tmem_SFA(cute::_, cute::_, k_block_id), + tmem_SFB_mma(cute::_, cute::_, k_block_id)), + tile_rA(cute::_, cute::_, k_block_id, + prologue_stage_idx), + tile_rB(cute::_, cute::_, k_block_id, + prologue_stage_idx), + tmem_accumulators(cute::_, cute::_, cute::_, + epilogue_stage_idx)); + } tiled_mma.accumulate_ = cute::UMMA::ScaleOut::One; } @@ -971,11 +1059,18 @@ struct CollectiveMainloop { ++accumulator_pipe_producer_state; scheduler.advance(); - next_tile_ready = scheduler.is_valid(); - if (next_tile_ready) { - accumulator_pipeline.producer_acquire( - accumulator_pipe_producer_state); - mainloop_pipeline.consumer_wait(mainloop_pipe_consumer_state); + + if constexpr (!KStreamK) { + // Prefetch: acquire the next tile's accumulator stage and + // wait on its first mainloop stage now, so the next + // iteration's MMA issue path starts with data ready. + next_tile_ready = scheduler.is_valid(); + if (next_tile_ready) { + accumulator_pipeline.producer_acquire( + accumulator_pipe_producer_state); + mainloop_pipeline.consumer_wait( + mainloop_pipe_consumer_state); + } } // TMEM overlap sync: wait for the overlap warp-group to finish diff --git a/csrc/kernel/gemm/stream_k_reduce.cuh b/csrc/kernel/gemm/stream_k_reduce.cuh new file mode 100644 index 0000000..d14ead0 --- /dev/null +++ b/csrc/kernel/gemm/stream_k_reduce.cuh @@ -0,0 +1,108 @@ +// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once +#include +#include + +#include + +// Reduction pass for tail-only stream-K (see tile_scheduler.h). +// +// The first `tail_base` cluster-tiles are data-parallel and written straight +// to D. Each of the remaining `rem` tiles is split into `splits` K-chunks, each +// writing a raw fp32 partial to its own workspace slot: +// +// partial[ ((t * splits + s) * num_cta + v) ][ cta_m ][ block_n ] +// +// (v = CTA index inside the cluster). This kernel sums the `splits` partials of +// each tail tile and casts to TypeD in place in D; cost scales with +// rem*splits only. A shared fp32 buffer with atomicAdd is slower (address +// contention serializes the epilogue stores). +template +__global__ void stream_k_reduce_kernel(TypeD* __restrict__ ptr_d, + float const* __restrict__ ptr_partial, + int tail_base, int rem, int splits, + int ctm, int ctn, bool m_fast, int out_n, + int64_t total_vec) { + int64_t idx = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (idx >= total_vec) { + return; + } + + // Unflatten: [t][v][cta_m][block_n], 4 columns per thread (scalar is + // issue-bound). BlockN % 4 == 0 and slots are CtaM*BlockN floats, so the + // float4 loads and 4x TypeD store are naturally aligned. + constexpr int kVec = 4; + constexpr int kColVecs = BlockN / kVec; + const int col = static_cast(idx % kColVecs) * kVec; + int64_t rest = idx / kColVecs; + const int row = static_cast(rest % CtaM); + rest /= CtaM; + const int v = static_cast(rest % NumCta); + const int t = static_cast(rest / NumCta); + + // Sum the `splits` partials of these elements. + float4 acc = make_float4(0.f, 0.f, 0.f, 0.f); + const int64_t slot_stride = static_cast(CtaM) * BlockN; + const int64_t within = static_cast(row) * BlockN + col; + for (int s = 0; s < splits; ++s) { + const int64_t slot = + (static_cast(t) * splits + s) * NumCta + v; + const float4 p = *reinterpret_cast( + ptr_partial + slot * slot_stride + within); + acc.x += p.x; + acc.y += p.y; + acc.z += p.z; + acc.w += p.w; + } + + // Map the tail work id to cluster coords as the scheduler's linear path + // does. + const int base_tile = tail_base + t; + int cluster_m, cluster_n; + if (m_fast) { + cluster_m = base_tile % ctm; + cluster_n = base_tile / ctm; + } else { + cluster_m = base_tile / ctn; + cluster_n = base_tile % ctn; + } + + const int64_t out_row = + (static_cast(cluster_m) * NumCta + v) * CtaM + row; + const int64_t out_col = static_cast(cluster_n) * BlockN + col; + cutlass::AlignedArray out; + out[0] = static_cast(acc.x); + out[1] = static_cast(acc.y); + out[2] = static_cast(acc.z); + out[3] = static_cast(acc.w); + *reinterpret_cast*>( + &ptr_d[out_row * out_n + out_col]) = out; +} + +template +inline void launch_stream_k_reduce(TypeD* ptr_d, float const* ptr_partial, + int tail_base, int rem, int splits, int ctm, + int ctn, bool m_fast, int out_n, + cudaStream_t stream) { + const int64_t total_vec = + static_cast(rem) * NumCta * CtaM * (BlockN / 4); + constexpr int kBlock = 256; + const int64_t grid = (total_vec + kBlock - 1) / kBlock; + stream_k_reduce_kernel + <<(grid), kBlock, 0, stream>>>( + ptr_d, ptr_partial, tail_base, rem, splits, ctm, ctn, m_fast, out_n, + total_vec); +} diff --git a/csrc/kernel/gemm/tile_scheduler.cuh b/csrc/kernel/gemm/tile_scheduler.cuh index 44fb968..b44148a 100644 --- a/csrc/kernel/gemm/tile_scheduler.cuh +++ b/csrc/kernel/gemm/tile_scheduler.cuh @@ -57,6 +57,19 @@ struct TileScheduler { static constexpr int kExpertClusterRows = kExpertTileSize * kExpertClusterTiles; + // --- Preamble-cost specializations --- + // The constructor runs in every warp of the CTA and is pure per-CTA + // preamble; these constants let the compiler drop provably dead parts. + // + // kAlwaysCompact: host sets use_compact_sched = (S == 1), and S > 1 only + // with UseTileSwizzle, so without swizzle only the compact path is + // reachable (tile_num_m_/tile_num_n_ are then dead too). + static constexpr bool kAlwaysCompact = !UseTileSwizzle; + // kIsSingleCtaCluster: cluster == CTA, so cluster queries reduce to + // gridDim/blockIdx (cheaper than CuTe's %%nclusterid/%%clusterid reads). + static constexpr bool kIsSingleCtaCluster = + (KernelTraits::KNumCTA == 1) && (cute::size(ClusterShape_MNK{}) == 1); + struct Params { int m; int n; @@ -68,25 +81,53 @@ struct TileScheduler { int expert_ctm; // per-expert cluster-tiles in M int expert_ctn; // per-expert cluster-tiles in N int total_tiles; // num_logical_experts * tiles_per_expert - cutlass::FastDivmod divmod_tiles; // ÷ tiles_per_expert - cutlass::FastDivmod divmod_ss; // ÷ S*S - cutlass::FastDivmod divmod_blocks; // ÷ blocks along the fast dim - cutlass::FastDivmod divmod_s; // ÷ S - - // Other compact state is derived on device (no D2H sync). - bool use_compact_sched; + // Host-precomputed fast divmod (avoid runtime integer division) + cutlass::FastDivmod divmod_tiles; // ÷ tiles_per_expert + cutlass::FastDivmod divmod_ss; // ÷ S*S + cutlass::FastDivmod + divmod_blocks; // ÷ blocks_fast (mode-dependent, see below) + cutlass::FastDivmod divmod_s; // ÷ S + + // Compact scheduling flag (set by host, all other compact state + // computed on device — no D2H sync needed). + bool use_compact_sched; // true for Masked mode with linear path (S=1) int batch_own_tiles; cutlass::FastDivmod divmod_batch_period; cutlass::FastDivmod divmod_slow_tiles; cutlass::FastDivmod divmod_own_tiles; int batch_valid_tiles; float batch_per_tile; + + // Linear-path traversal orientation (Naive only; see + // to_underlying_arguments). + // false → N-fast (tile_id ÷ expert_ctn): consecutive tiles sweep N. + // true → M-fast (tile_id ÷ expert_ctm): consecutive tiles sweep M. + bool traverse_m_fast; + + // Contiguous-range tile assignment instead of strided (Batch SwapAB + // only). See to_underlying_arguments. + bool chunked_assign; + + // --- Tail-only stream-K (Naive only; streamk_rem == 0 disables) --- + // C clusters over W tiles: the first streamk_tail_base = (W/C)*C tiles + // stay data-parallel (full K); each of the remaining streamk_rem tiles + // is split into streamk_splits K-chunks on different clusters, so the + // makespan drops from ceil(W/C) to W/C + 1/splits tile-times and only + // the tail needs fp32 partials. Fused work-id space, one launch: + // [0, tail_base) whole tiles, full K range + // [tail_base, tail_base + rem * splits) (tail tile, K-chunk) pairs + int streamk_tail_base; + int streamk_rem; + int streamk_splits; + int k_tiles; // ceil_div(k, KBlockK); chunk bounds are derived from it }; static Params to_underlying_arguments(int m, int n, int num_experts = 0, int max_m_per_expert = 0, int const* masked_m = nullptr, - int const* expert_ids = nullptr) { + int const* expert_ids = nullptr, + int num_clusters = 0, + int k_tiles = 0) { constexpr int kTileM = cute::size<0>(TileShape{}); constexpr int kTileN = cute::size<1>(TileShape{}); @@ -142,12 +183,106 @@ struct TileScheduler { int tiles_per_expert = blocks_m * blocks_n * S * S; int total_tiles = num_logical_experts * tiles_per_expert; - int divmod_blocks_divisor = SwapAB ? blocks_m : blocks_n; + // --- Linear-path traversal orientation (Naive only) --- + // The operand indexed by the fast dimension stays L2-resident; the + // other is streamed once. Keep the smaller one resident: + // N-fast → B (N×K) resident; right when N <= M. + // M-fast → A (M×K) resident; right when M < N. + // Naive non-SwapAB uses M-fast when m < n (N-fast re-reads a large B + // from DRAM every wave). HALOPS_TRAVERSE_MFAST=0 forces N-fast. + bool traverse_m_fast = false; + if constexpr (KernelTraits::KernelType == KernelMode::Dense && + !SwapAB) { + static const bool mfast_enabled = [] { + const char* e = std::getenv("HALOPS_TRAVERSE_MFAST"); + return e == nullptr || e[0] != '0'; + }(); + traverse_m_fast = mfast_enabled && (S == 1) && (m < n); + } + + int divmod_blocks_divisor; + if (S == 1 && traverse_m_fast) { + divmod_blocks_divisor = expert_ctm; + } else { + divmod_blocks_divisor = SwapAB ? blocks_m : blocks_n; + } cutlass::FastDivmod divmod_tiles(tiles_per_expert); cutlass::FastDivmod divmod_ss(S * S); cutlass::FastDivmod divmod_blocks(divmod_blocks_divisor); cutlass::FastDivmod divmod_s(S); + // --- Tail-only stream-K decomposition (Naive only; see Params) --- + // splits must divide k_tiles so every chunk has the same length. + int streamk_tail_base = total_tiles; + int streamk_rem = 0; + int streamk_splits = 1; + // KSupportsStreamK (kernel_traits.h) limits this to BF16 dense without + // bias/alpha (they cannot deposit a partial) and without SwapAB. + if constexpr (KernelTraits::KSupportsStreamK) { + // Default ON; rejected shapes keep streamk_rem == 0 and run the + // plain data-parallel path (no workspace, no reduce launch). + // HALOPS_STREAMK=0 forces the data-parallel path. + static const bool streamk_enabled = [] { + const char* e = std::getenv("HALOPS_STREAMK"); + return e == nullptr || e[0] != '0'; + }(); + const int C = num_clusters; + // Grid-underfill extension: total_tiles > 0 (not > C) also admits + // whole == 0 (thin M, total_tiles < C), where every tile is split + // so the existing tiles occupy more SMs. p_cap = C / rem keeps + // near-full grids at p = 1 and bounds the workspace at <= C slots. + // HALOPS_STREAMK_FILL=0 restores the tail-only gate. + static const bool streamk_fill = [] { + const char* e = std::getenv("HALOPS_STREAMK_FILL"); + return e == nullptr || e[0] != '0'; + }(); + const bool size_ok = + streamk_fill ? (total_tiles > 0) : (total_tiles > C); + if (streamk_enabled && S == 1 && C > 0 && k_tiles > 0 && size_ok) { + const int whole = total_tiles / C; + const int rem = total_tiles - whole * C; + // Split only when the remainder idles >= 5% of total SM-time + // (break-even for the rem*splits partial-tile reduction). + const bool worth_it = + rem > 0 && (C - rem) * 20 >= (whole + 1) * C; + if (worth_it) { + // Use the largest p <= min(C / rem, 8) dividing k_tiles: + // the overhead is fixed, not per-split. + // HALOPS_STREAMK_P=

overrides the cap. + int p_cap = C / rem < 8 ? C / rem : 8; + static const int p_forced = [] { + const char* e = std::getenv("HALOPS_STREAMK_P"); + return e != nullptr ? atoi(e) : 0; + }(); + if (p_forced > 0) { + p_cap = p_forced; + } + int p = 1; + for (int cand = p_cap; cand >= 2; --cand) { + if (k_tiles % cand == 0) { + p = cand; + break; + } + } + if (p >= 2 && (whole > 0 || p >= 4)) { + // Underfill gate: with whole == 0, only p >= 4 repays + // the fp32 workspace round-trip and reduce launch. + + streamk_tail_base = whole * C; + streamk_rem = rem; + streamk_splits = p; + // Tail items become the (whole+1)-th item of clusters + // 0..rem*p-1, reusing the resident mainloop pipeline. + total_tiles = streamk_tail_base + rem * p; + } + } + } + } + + // Compact scheduling: enabled for Masked and Contiguous modes with S=1 + // (linear path). All compact scheduling state (total_valid_tiles, + // expert cache) is computed on the device — no D2H copy or host-side + // masked_m access. bool use_compact_sched = false; if (S == 1) { use_compact_sched = true; @@ -179,6 +314,23 @@ struct TileScheduler { kExpertClusterRows) : 0.f; + // --- Contiguous-range assignment (Batch SwapAB only) --- + // SwapAB numbering keeps one item's N segments consecutive, but the + // persistent stride spreads them over different CTAs, so the shared + // activation's L2 reuse becomes a race. Chunked assignment gives CTA i + // the range [i*chunk, (i+1)*chunk), so one CTA processes them + // back-to-back. Only when expert_ctm > 1 (otherwise nothing is + // shared). HALOPS_BATCH_CHUNK=0 restores the stride. + bool chunked_assign = false; + if constexpr (KernelTraits::KernelType == KernelMode::Batch && SwapAB && + KernelTraits::KIsBF16) { + static const bool chunk_enabled = [] { + const char* e = std::getenv("HALOPS_BATCH_CHUNK"); + return e == nullptr || e[0] != '0'; + }(); + chunked_assign = chunk_enabled && S == 1 && expert_ctm > 1; + } + return {m, n, num_experts, @@ -199,7 +351,13 @@ struct TileScheduler { cutlass::FastDivmod(SwapAB ? expert_ctm : expert_ctn), cutlass::FastDivmod(batch_own_tiles > 0 ? batch_own_tiles : 1), batch_valid_tiles, - batch_per_tile}; + batch_per_tile, + traverse_m_fast, + chunked_assign, + streamk_tail_base, + streamk_rem, + streamk_splits, + k_tiles}; } uint32_t tile_num_m_; @@ -212,6 +370,11 @@ struct TileScheduler { uint32_t cluster_num_; // stride = number of clusters uint32_t current_tile_id_; // current position in global tile space + // Chunked assignment (Batch SwapAB): step is 1 and each CTA iterates a + // contiguous range ending at tile_end_. Otherwise step = cluster_num_ and + // the range ends at the total tile count. + uint32_t advance_step_; + uint32_t tile_end_; uint32_t expert_ctm_; uint32_t expert_ctn_; @@ -234,6 +397,18 @@ struct TileScheduler { uint32_t batch_valid_tiles_; float batch_per_tile_; uint32_t act_row0_; + bool traverse_m_fast_; + bool chunked_assign_; + + // Tail-only stream-K state (see Params). streamk_rem_ == 0 disables. + uint32_t streamk_tail_base_; + uint32_t streamk_rem_; + uint32_t streamk_splits_; + uint32_t k_tiles_; + // Resolved for the current work item by find_next_valid_tile(). + uint32_t k_begin_; + uint32_t k_end_; + int partial_slot_; // -1 = write straight to D; else index into the fp32 ws uint32_t total_valid_tiles_; // sum of valid cluster-tiles across all experts // tile ids only grow, so the expert cache is advanced by forward scan. @@ -315,29 +490,55 @@ struct TileScheduler { divmod_slow_tiles_(params.divmod_slow_tiles), divmod_own_tiles_(params.divmod_own_tiles), batch_valid_tiles_(params.batch_valid_tiles), - batch_per_tile_(params.batch_per_tile) { - tile_num_m_ = cute::ceil_div(params.m, cute::size<0>(TileShape{})); - tile_num_n_ = cute::ceil_div(params.n, cute::size<1>(TileShape{})); - - cluster_num_ = - cute::cluster_grid_dims().x * cute::cluster_grid_dims().y; - int cluster_idx = - cute::cluster_id_in_grid().x * cute::cluster_grid_dims().y + - cute::cluster_id_in_grid().y; - - cute::Layout cluster_layout_vmnk = - cute::tiled_divide(cute::make_layout(ClusterShape_MNK{}), - cute::make_tile(typename TiledMma::AtomThrID{})); - int block_rank = cute::block_rank_in_cluster(); - auto cta_coord_vmnk = cluster_layout_vmnk.get_flat_coord(block_rank); - - cluster_m_tiles_ = cute::size<1>(cluster_layout_vmnk); - cluster_n_tiles_ = cute::size<2>(cluster_layout_vmnk); - cta_m_offset_ = cute::get<1>(cta_coord_vmnk); - cta_n_offset_ = cute::get<2>(cta_coord_vmnk); - cta_v_ = cute::get<0>(cta_coord_vmnk); - - if (use_compact_sched_) { + batch_per_tile_(params.batch_per_tile), + traverse_m_fast_(params.traverse_m_fast), + chunked_assign_(params.chunked_assign), + streamk_tail_base_(params.streamk_tail_base), + streamk_rem_(params.streamk_rem), + streamk_splits_(params.streamk_splits), + k_tiles_(params.k_tiles) { + // tile_num_m_/tile_num_n_ only feed the non-compact bounds check, so + // skip the two ceil_div's when that path is statically unreachable. + if constexpr (!kAlwaysCompact) { + tile_num_m_ = ceil_div(params.m, size<0>(TileShape{})); + tile_num_n_ = ceil_div(params.n, size<1>(TileShape{})); + } + + int cluster_idx; + if constexpr (kIsSingleCtaCluster) { + // cluster == CTA: read gridDim/blockIdx directly (cheaper than + // CuTe's %%nclusterid / %%clusterid reads). + cluster_num_ = gridDim.x * gridDim.y; + cluster_idx = blockIdx.x * gridDim.y + blockIdx.y; + // Single-CTA cluster: block_rank 0, flat coord (0,0,0). + cluster_m_tiles_ = kClusterMTiles; + cluster_n_tiles_ = kClusterNTiles; + cta_m_offset_ = 0; + cta_n_offset_ = 0; + cta_v_ = 0; + } else { + cluster_num_ = + cute::cluster_grid_dims().x * cute::cluster_grid_dims().y; + cluster_idx = + cute::cluster_id_in_grid().x * cute::cluster_grid_dims().y + + cute::cluster_id_in_grid().y; + + cute::Layout cluster_layout_vmnk = cute::tiled_divide( + cute::make_layout(ClusterShape_MNK{}), + cute::make_tile(typename TiledMma::AtomThrID{})); + int block_rank = cute::block_rank_in_cluster(); + auto cta_coord_vmnk = + cluster_layout_vmnk.get_flat_coord(block_rank); + + cluster_m_tiles_ = cute::size<1>(cluster_layout_vmnk); + cluster_n_tiles_ = cute::size<2>(cluster_layout_vmnk); + cta_m_offset_ = cute::get<1>(cta_coord_vmnk); + cta_n_offset_ = cute::get<2>(cta_coord_vmnk); + cta_v_ = get<0>(cta_coord_vmnk); + } + + // Compute compact scheduling state on device + if (kAlwaysCompact || use_compact_sched_) { if constexpr (IsBatch) { total_valid_tiles_ = batch_valid_tiles_; cached_expert_ = 0; @@ -351,7 +552,10 @@ struct TileScheduler { total_valid_tiles_ = total_tiles_; cached_expert_ = 0; cached_expert_start_ = 0; - cached_expert_end_ = total_tiles_; + // Single logical expert: the expert-cache fast path must + // always hit (the slow path dereferences masked_m, nullptr + // here), including for folded stream-K base tile ids. + cached_expert_end_ = 0xFFFFFFFFu; } else { total_valid_tiles_ = 0; for (uint32_t e = 0; e < num_experts_; e++) { @@ -368,7 +572,32 @@ struct TileScheduler { cached_expert_end_ = 0; } + // Defaults for the non-compact path (stream-K is compact/Naive-only). + k_begin_ = 0; + k_end_ = k_tiles_; + partial_slot_ = -1; + + // Start at this cluster's first tile current_tile_id_ = cluster_idx; + advance_step_ = cluster_num_; + // Strided default; stream-K tail work ids lie inside + // total_valid_tiles_ by construction. + tile_end_ = total_valid_tiles_; + if (chunked_assign_) { + // Range [cluster_idx*chunk, +chunk), clamped to the tile count. + uint32_t chunk = + (total_valid_tiles_ + cluster_num_ - 1) / cluster_num_; + uint32_t base = cluster_idx * chunk; + current_tile_id_ = base; + tile_end_ = base + chunk; + if (tile_end_ > total_valid_tiles_ || chunk == 0) { + tile_end_ = total_valid_tiles_; + } + if (current_tile_id_ > total_valid_tiles_) { + current_tile_id_ = total_valid_tiles_; + } + advance_step_ = 1; + } find_next_valid_tile(); } @@ -381,9 +610,16 @@ struct TileScheduler { CUTLASS_DEVICE uint32_t max_m_per_expert() const { return max_m_per_expert_; } + // K-tile range of the current work item. Producer and consumer MUST use + // the same bounds or the mainloop pipeline deadlocks. + CUTLASS_DEVICE uint32_t k_begin() const { return k_begin_; } + CUTLASS_DEVICE uint32_t k_end() const { return k_end_; } + // >= 0 when this work item computed only a K-slice and must deposit an + // fp32 partial instead of the final bf16 result. + CUTLASS_DEVICE int partial_slot() const { return partial_slot_; } CUTLASS_DEVICE void advance() { - current_tile_id_ += cluster_num_; + current_tile_id_ += advance_step_; find_next_valid_tile(); } @@ -450,6 +686,10 @@ struct TileScheduler { uint32_t local_cluster_n = q; cluster_m = local_cluster_m; cluster_n = expert_first_cluster_tile(expert) + local_cluster_n; + } else if (traverse_m_fast_) { + // M-fast: divisor was expert_ctm_, so r indexes M and q indexes N. + cluster_m = expert_first_cluster_tile(expert) + static_cast(r); + cluster_n = static_cast(q); } else { uint32_t local_cluster_m = q; uint32_t local_cluster_n = r; @@ -521,30 +761,64 @@ struct TileScheduler { // Scan forward from current_tile_id_ to find the next valid tile, // caching its coordinates in m_idx_/n_idx_/expert_idx_/is_valid_. CUTLASS_DEVICE void find_next_valid_tile() { - if constexpr (KDenseW8A8MXFP8 && !UseTileSwizzle) { - while (current_tile_id_ < total_tiles_) { - int q, r; - divmod_blocks_.fast_divmod(q, r, - static_cast(current_tile_id_)); - if constexpr (SwapAB) { - m_idx_ = r * cluster_m_tiles_ + cta_m_offset_; - n_idx_ = q * cluster_n_tiles_ + cta_n_offset_; - } else { - m_idx_ = q * cluster_m_tiles_ + cta_m_offset_; - n_idx_ = r * cluster_n_tiles_ + cta_n_offset_; + // W8A8-dense fast path (quantized only): every tile is valid, so a + // plain divmod resolves the tile without the compact-scan bookkeeping. + // Guarded to !KIsBF16 (BF16 needs the stream-K fold and M-fast + // traversal handled in the compact path below) and !traverse_m_fast_ + // (the divmod orientation below assumes N-fast). + if constexpr (KDenseW8A8MXFP8 && !UseTileSwizzle && + !KernelTraits::KIsBF16) { + if (!traverse_m_fast_) { + while (current_tile_id_ < total_tiles_) { + int q, r; + divmod_blocks_.fast_divmod( + q, r, static_cast(current_tile_id_)); + if constexpr (SwapAB) { + m_idx_ = r * cluster_m_tiles_ + cta_m_offset_; + n_idx_ = q * cluster_n_tiles_ + cta_n_offset_; + } else { + m_idx_ = q * cluster_m_tiles_ + cta_m_offset_; + n_idx_ = r * cluster_n_tiles_ + cta_n_offset_; + } + expert_idx_ = 0; + is_valid_ = true; + return; } - expert_idx_ = 0; - is_valid_ = true; + is_valid_ = false; return; } - is_valid_ = false; - return; } - if (use_compact_sched_) { - while (current_tile_id_ < total_valid_tiles_) { + if (kAlwaysCompact || use_compact_sched_) { + // Compact path: the tile space only contains valid cluster-tiles, + // so we skip directly to the current tile without iterating through + // large swaths of padding. Only need a lightweight per-CTA check + // for the edge case where the last cluster row of an expert has + // some CTAs with tiles beyond masked_m. With chunked_assign_ the + // per-CTA range ends at tile_end_ instead of total_valid_tiles_. + while (current_tile_id_ < tile_end_) { uint32_t cluster_m, cluster_n, expert; - uint32_t tile_id = current_tile_id_; - tile_id_to_coords_compact(tile_id, cluster_m, cluster_n, + // Stream-K: ids >= streamk_tail_base_ are (tail tile, K-chunk) + // pairs. Fold to the base tile id and resolve the K range and + // partial slot here so all roles see identical values. + uint32_t base_tile_id = current_tile_id_; + k_begin_ = 0; + k_end_ = k_tiles_; + partial_slot_ = -1; + if constexpr (KernelTraits::KernelType == KernelMode::Dense) { + if (streamk_rem_ > 0 && + current_tile_id_ >= streamk_tail_base_) { + uint32_t local = current_tile_id_ - streamk_tail_base_; + uint32_t t = local / streamk_splits_; + uint32_t s = local - t * streamk_splits_; + base_tile_id = streamk_tail_base_ + t; + // streamk_splits_ divides k_tiles_ (host-enforced). + uint32_t chunk = k_tiles_ / streamk_splits_; + k_begin_ = s * chunk; + k_end_ = k_begin_ + chunk; + partial_slot_ = static_cast(local); + } + } + tile_id_to_coords_compact(base_tile_id, cluster_m, cluster_n, expert); uint32_t m_idx = cluster_m * cluster_m_tiles_ + cta_m_offset_; diff --git a/csrc/kernel/gemm/utils.cuh b/csrc/kernel/gemm/utils.cuh index 8e216be..d9e7cde 100644 --- a/csrc/kernel/gemm/utils.cuh +++ b/csrc/kernel/gemm/utils.cuh @@ -64,6 +64,7 @@ struct GemmKernelConfig { static constexpr bool AddBias = false; static constexpr bool SwapAB = false; static constexpr bool KIsFP4 = false; + static constexpr bool KIsBF16 = false; static constexpr bool HasAlpha = false; // Scale-factor vector size: 16 = NVFP4 (UE4M3), 32 = MXFP4 (UE8M0). Fixes // the MMA and SF atom shapes, so it is a compile-time config. @@ -72,8 +73,16 @@ struct GemmKernelConfig { static constexpr bool SkipTmemFence = false; static constexpr EpilogueOp KEpiOp = EpilogueOp::Identity; static constexpr bool KSwapSfbRun = false; + // Number of epilogue warp groups; 0 = auto (SwapAB ? 1 : 2). + // KEpiComputeN = KBlockN / count must be >= 32 when CtaM == 64, so narrow + // tiles (e.g. 64x32) need 1. Also drops the inter-warp-group barrier. + static constexpr int KEpilogueWarpGroupsOverride = 0; + // Force KEpiNeedsNPredicate even for power-of-two KBlockN, so a wide tile + // can serve N % KBlockN != 0 (e.g. N=1600 on a 128-wide tile). + static constexpr bool KForceEpiNPredicate = false; }; +// BF16 tile definitions live in gemm_tile.cuh alongside the W8A8/W4A4 ones. static constexpr int get_num_warps(int load_c_warp_id, bool add_bias) { int last_warp = add_bias ? load_c_warp_id : (load_c_warp_id - 1); return ((last_warp + 4) / 4) * 4; diff --git a/halops/gemm/batch_gemm.py b/halops/gemm/batch_gemm.py index baedb6d..b0e289a 100644 --- a/halops/gemm/batch_gemm.py +++ b/halops/gemm/batch_gemm.py @@ -27,8 +27,8 @@ def batch_gemm( input: torch.Tensor, weight: torch.Tensor, - sfa: torch.Tensor, - sfb: torch.Tensor, + sfa: Optional[torch.Tensor], + sfb: Optional[torch.Tensor], output: torch.Tensor, bias: Optional[torch.Tensor] = None, alpha: Optional[torch.Tensor] = None, @@ -71,7 +71,9 @@ def batch_gemm( value per batch item. Required for ``w4a4-nvfp4``; not accepted for ``w4a4-mxfp4``. sm_count: Number of SMs to use (-1 for all available). - mode: ``"w8a8-mxfp8"``, ``"w4a4-mxfp4"`` or ``"w4a4-nvfp4"``. + mode: ``"w8a8-mxfp8"``, ``"w4a4-mxfp4"`` or ``"w4a4-nvfp4"`` for + quantized GEMM, or ``"bf16"`` for native BF16 GEMM (no + quantization; pass ``sfa=None, sfb=None``). epilogue: ``EpilogueOp.Identity``, ``EpilogueOp.Quant``, ``EpilogueOp.GateMulQuant`` or ``EpilogueOp.SigmoidGateMulQuant`` (``w8a8-mxfp8``: float8_e4m3fn output, the result (times ``gate``, @@ -100,6 +102,11 @@ def batch_gemm( >>> out = torch.empty(m, b * n, dtype=torch.bfloat16, device="cuda") >>> batch_gemm(x, w, sfa, sfb, out, mode="w8a8-mxfp8") """ + if sfa is None: + sfa = torch.empty(0, dtype=torch.uint8, device=input.device) + if sfb is None: + sfb = torch.empty(0, dtype=torch.uint8, device=input.device) + halops_kernel.batch_gemm( input, weight, diff --git a/halops/gemm/dense_gemm.py b/halops/gemm/dense_gemm.py index ce367d0..a82b250 100644 --- a/halops/gemm/dense_gemm.py +++ b/halops/gemm/dense_gemm.py @@ -44,8 +44,8 @@ def interleave_gate_up(t: torch.Tensor) -> torch.Tensor: def dense_gemm( input: torch.Tensor, weight: torch.Tensor, - sfa: torch.Tensor, - sfb: torch.Tensor, + sfa: Optional[torch.Tensor], + sfb: Optional[torch.Tensor], output: torch.Tensor, bias: Optional[torch.Tensor] = None, alpha: Optional[torch.Tensor] = None, @@ -87,8 +87,9 @@ def dense_gemm( alpha: Optional float32 scaling factor with shape [1]. Required for ``w4a4-nvfp4``; not accepted for ``w4a4-mxfp4``. sm_count: Number of SMs to use (-1 for all available). - mode: Quantization mode: ``"w8a8-mxfp8"``, ``"w4a4-mxfp4"`` or - ``"w4a4-nvfp4"``. + mode: ``"w8a8-mxfp8"``, ``"w4a4-mxfp4"`` or ``"w4a4-nvfp4"`` for + quantized GEMM, or ``"bf16"`` for native BF16 GEMM (no + quantization; pass ``sfa=None, sfb=None``). use_pdl: Enable Programmatic Dependent Launch (on by default). epilogue: ``EpilogueOp.Identity``, ``EpilogueOp.Sigmoid`` (bfloat16 ``sigmoid(input @ weight^T + bias)``) or ``EpilogueOp.SituQuant`` @@ -117,6 +118,11 @@ def dense_gemm( >>> out = torch.empty(m, n, dtype=torch.bfloat16, device="cuda") >>> dense_gemm(x, w, sfa, sfb, out, mode="w8a8-mxfp8") """ + if sfa is None: + sfa = torch.empty(0, dtype=torch.uint8, device=input.device) + if sfb is None: + sfb = torch.empty(0, dtype=torch.uint8, device=input.device) + halops_kernel.dense_gemm( input, weight, diff --git a/halops/gemm/group_contiguous_gemm.py b/halops/gemm/group_contiguous_gemm.py index 390333a..7defd0f 100644 --- a/halops/gemm/group_contiguous_gemm.py +++ b/halops/gemm/group_contiguous_gemm.py @@ -26,8 +26,8 @@ def group_contiguous_gemm( input: torch.Tensor, weight: torch.Tensor, - sfa: torch.Tensor, - sfb: torch.Tensor, + sfa: Optional[torch.Tensor], + sfb: Optional[torch.Tensor], expert_ids: torch.Tensor, output: torch.Tensor, bias: Optional[torch.Tensor] = None, @@ -71,8 +71,9 @@ def group_contiguous_gemm( ``w4a8-mxfp4``. sm_count: Number of SMs to use (-1 for all available). mode: ``"w8a8-mxfp8"``, ``"w4a4-mxfp4"``, ``"w4a4-nvfp4"`` or - ``"w4a8-mxfp4"`` (FP8 activation x MXFP4 weight). For - ``w4a8-mxfp4`` the per-expert M ``M // num_experts`` must be 64 + ``"w4a8-mxfp4"`` (FP8 activation x MXFP4 weight), or ``"bf16"`` for + native BF16 GEMM (no quantization; pass ``sfa=None, sfb=None``). + For ``w4a8-mxfp4`` the per-expert M ``M // num_experts`` must be 64 or a multiple of 128; N must be a multiple of 128 when that M is at most 128, else a multiple of 256, and K a multiple of 256. @@ -95,6 +96,11 @@ def group_contiguous_gemm( >>> out = torch.empty(m, n, dtype=torch.bfloat16, device="cuda") >>> group_contiguous_gemm(x, w, sfa, sfb, expert_ids, out, mode="w8a8-mxfp8") """ + if sfa is None: + sfa = torch.empty(0, dtype=torch.uint8, device=input.device) + if sfb is None: + sfb = torch.empty(0, dtype=torch.uint8, device=input.device) + halops_kernel.group_contiguous_gemm( input, weight, diff --git a/halops/gemm/group_masked_gemm.py b/halops/gemm/group_masked_gemm.py index 7e485d0..e25d2ea 100644 --- a/halops/gemm/group_masked_gemm.py +++ b/halops/gemm/group_masked_gemm.py @@ -26,8 +26,8 @@ def group_masked_gemm( input: torch.Tensor, weight: torch.Tensor, - sfa: torch.Tensor, - sfb: torch.Tensor, + sfa: Optional[torch.Tensor], + sfb: Optional[torch.Tensor], masked_m: torch.Tensor, output: torch.Tensor, bias: Optional[torch.Tensor] = None, @@ -73,7 +73,9 @@ def group_masked_gemm( and K a multiple of 256. sm_count: Number of SMs to use (-1 for all available). mode: ``"w8a8-mxfp8"``, ``"w4a4-mxfp4"``, ``"w4a4-nvfp4"`` or - ``"w4a8-mxfp4"`` (FP8 activation x MXFP4 weight). + ``"w4a8-mxfp4"`` for quantized GEMM, or ``"bf16"`` for + native BF16 GEMM (no quantization; pass ``sfa=None, + sfb=None``). Returns: None. The result is written in-place to output. @@ -97,6 +99,11 @@ def group_masked_gemm( ... max_m_per_expert=max_m_per_expert, mode="w8a8-mxfp8", ... ) """ + if sfa is None: + sfa = torch.empty(0, dtype=torch.uint8, device=input.device) + if sfb is None: + sfb = torch.empty(0, dtype=torch.uint8, device=input.device) + halops_kernel.group_masked_gemm( input, weight, diff --git a/tests/test_gemm_bf16.py b/tests/test_gemm_bf16.py new file mode 100644 index 0000000..53dc6b1 --- /dev/null +++ b/tests/test_gemm_bf16.py @@ -0,0 +1,139 @@ +""" +# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" + +import numpy as np +import torch + +from halops import dense_gemm + + +torch.manual_seed(2026) +torch.cuda.manual_seed_all(2026) +torch.set_default_device("cuda") + + +def _run_bf16_gemm_case(m, n, k): + print(f"[BF16 GEMM] m={m}, n={n}, k={k}") + x = torch.randn([m, k], dtype=torch.bfloat16) + w = torch.randn([n, k], dtype=torch.bfloat16) + out = torch.empty([m, n], dtype=torch.bfloat16) + + ref = torch.matmul(x.to(torch.float32), w.to(torch.float32).T).to(torch.bfloat16) + dense_gemm(x, w, None, None, out, mode="bf16") + + diff = (out.to(torch.float32) - ref.to(torch.float32)).abs() + print( + f"[BF16 GEMM] max_diff={diff.max().item():.6f}, " + f"mean_diff={diff.mean().item():.6f}" + ) + np.testing.assert_allclose( + out.to(torch.float32).cpu().numpy(), + ref.to(torch.float32).cpu().numpy(), + rtol=2e-2, + atol=2e-2, + ) + + +def _expect_runtime_error(fn, expected): + try: + fn() + except RuntimeError as e: + msg = str(e) + assert expected in msg, f"expected '{expected}' in RuntimeError, got: {msg}" + print(f" [PASS] caught expected RuntimeError: {expected}") + else: + raise AssertionError(f"expected RuntimeError containing: {expected}") + + +def test_bf16_gemm_large_m(): + _run_bf16_gemm_case(4096, 256, 256) + + +def test_bf16_gemm_large_m_n1600(): + # Real production shape (MLA/DSA q_a_proj, bulk prefill): 1600 % 128 == 64, + # so it fits neither the 256- nor the 128-wide full-tile large-M rung. + # Covers 256x128x64_2CTA_Ntail end to end (predicated store at + # KSubTileN=64 granularity, N % 64 == 0 launch check). + _run_bf16_gemm_case(4096, 1600, 4096) + + +def test_bf16_gemm_large_m_n1600_ladder(): + # N=1600 tail (128-wide MMA, predicated store) across all production M + # values in benchmark/configs/gemm/dense_bf16.yaml. M=1024/2048 are + # mid-M and unaffected by the large-M Ntail change; included here to pin + # the N=1600 correctness baseline across every M rung in one place. + for m in (1024, 2048, 4096, 8192, 16384): + _run_bf16_gemm_case(m, 1600, 4096) + + +def test_bf16_gemm_large_m_n128(): + # Real production shape (DSA indexer proj): n=128 leaves the KBlockM=256 + # family under half a wave (32 / 64 CTAs of 152), so large-M steps M down + # instead of N -- covers the 64x64 and 64x128 rungs. + _run_bf16_gemm_case(4096, 128, 4096) + _run_bf16_gemm_case(8192, 128, 4096) + + +def test_bf16_gemm_mid_m(): + _run_bf16_gemm_case(128, 256, 256) + + +def test_bf16_gemm_small_m(): + # m < 128 -> 128x64x64 SwapAB small-M path. + # SwapAB maps weight(N-dim) to tile_M=128 (N % 128) and activation(M-dim) + # to tile_N=64 (M % 64), so use n=256 (multiple of 128) and m=64. + _run_bf16_gemm_case(64, 256, 256) + + +def test_bf16_gemm_small_m_deep_k(): + # thin-M with k >= 8192 -> 128x64x128 SwapAB rung (KBlockK=128). + _run_bf16_gemm_case(64, 4096, 8192) + + +def test_bf16_gemm_mid_m_odd_n(): + # N not a multiple of 128 -> mid-M 64x96 rung / predicated tail family. + _run_bf16_gemm_case(1024, 1536, 4096) + + +def test_bf16_gemm_unsupported_shapes(): + def run_bad_k(): + m, n, k = 128, 256, 96 + x = torch.empty([m, k], dtype=torch.bfloat16) + w = torch.empty([n, k], dtype=torch.bfloat16) + out = torch.empty([m, n], dtype=torch.bfloat16) + dense_gemm(x, w, None, None, out, mode="bf16") + + _expect_runtime_error(run_bad_k, "BF16 GEMM mid M K must be divisible by 64") + + def run_bad_dtype(): + m, n, k = 128, 256, 256 + x = torch.empty([m, k], dtype=torch.float16) + w = torch.empty([n, k], dtype=torch.bfloat16) + out = torch.empty([m, n], dtype=torch.bfloat16) + dense_gemm(x, w, None, None, out, mode="bf16") + + _expect_runtime_error(run_bad_dtype, "input must be bfloat16") + + +if __name__ == "__main__": + test_bf16_gemm_large_m() + test_bf16_gemm_large_m_n1600() + test_bf16_gemm_large_m_n1600_ladder() + test_bf16_gemm_large_m_n128() + test_bf16_gemm_mid_m() + test_bf16_gemm_small_m() + test_bf16_gemm_unsupported_shapes() + print("All BF16 GEMM tests passed!") diff --git a/tests/test_gemm_bf16_grouped.py b/tests/test_gemm_bf16_grouped.py new file mode 100644 index 0000000..25c7492 --- /dev/null +++ b/tests/test_gemm_bf16_grouped.py @@ -0,0 +1,172 @@ +""" +# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" + +# Native BF16 (mode="bf16") accuracy tests for the batch / grouped-masked / +# grouped-contiguous GEMM entry points. These share the self-developed +# CollectiveMainloop path with W8A8/W4A4 but take the compile-time KIsBF16 +# branch (no scale factors, no alpha). Golden reference is a plain fp32 matmul +# rounded to bf16, so tolerances are much tighter than the quantized paths. + +import numpy as np +import torch + +from halops import batch_gemm, group_contiguous_gemm, group_masked_gemm + +torch.manual_seed(2026) +torch.cuda.manual_seed_all(2026) +torch.set_default_device("cuda") + +# bf16 output is rounded once by the kernel and once by the reference; a couple +# of ulps of slack is enough. This is far tighter than fp8 (atol 2e-3 rtol 2e-2) +# in relative terms because there is no dequantization error. +RTOL = 1e-2 +ATOL = 1e-2 + + +def _assert_close(out, ref, tag): + out_np = out.to(torch.float32).cpu().numpy() + ref_np = ref.to(torch.float32).cpu().numpy() + diff = np.abs(out_np - ref_np) + print(f" {tag}: max_diff={diff.max():.6f}, mean_diff={diff.mean():.6f}") + np.testing.assert_allclose(out_np, ref_np, rtol=RTOL, atol=ATOL) + + +# ===================================================================== +# Batch GEMM (BF16) +# ===================================================================== + + +def _run_batch_bf16(B, M, N, K): + print(f"[BF16 batch] B={B}, M={M}, N={N}, K={K}") + x = torch.randn([B, M, K], dtype=torch.bfloat16) + w = torch.randn([B, N, K], dtype=torch.bfloat16) + out = torch.zeros([M, B * N], dtype=torch.bfloat16) + + # Golden: per-batch fp32 matmul, output[:, b * N:(b + 1) * N] = x[b] @ w[b]^T + ref = torch.matmul(x.to(torch.float32), w.to(torch.float32).transpose(1, 2)).to( + torch.bfloat16 + ) + + batch_gemm(x, w, None, None, out, mode="bf16") + + for b in range(B): + _assert_close(out[:, b * N : (b + 1) * N], ref[b], f"batch {b}") + print(f" [PASS] BF16 batch B={B}, M={M}, N={N}, K={K}") + + +def test_batch_bf16_mid_m(): + # total_m = 512 -> 128x256x64 mid path + _run_batch_bf16(B=4, M=128, N=256, K=128) + + +def test_batch_bf16_large_m(): + # total_m = 4096 -> 256x256x64 large path + _run_batch_bf16(B=4, M=1024, N=256, K=128) + + +# ===================================================================== +# Grouped masked GEMM (BF16) +# ===================================================================== + + +def _run_masked_bf16(num_experts, max_m_per_expert, N, K, masked_m): + print( + f"[BF16 masked] experts={num_experts}, max_m={max_m_per_expert}, " + f"N={N}, K={K}, masked_m={masked_m}" + ) + total_m = num_experts * max_m_per_expert + x = torch.randn([total_m, K], dtype=torch.bfloat16) + w = torch.randn([num_experts, N, K], dtype=torch.bfloat16) + out = torch.zeros([total_m, N], dtype=torch.bfloat16) + masked_m_t = torch.tensor(masked_m, dtype=torch.int32) + + group_masked_gemm( + x, + w, + None, + None, + masked_m_t, + out, + max_m_per_expert=max_m_per_expert, + mode="bf16", + ) + + # Golden + comparison per expert, valid rows only. + for e in range(num_experts): + m = masked_m[e] + if m == 0: + continue + start = e * max_m_per_expert + x_e = x[start : start + m, :].to(torch.float32) + w_e = w[e].to(torch.float32).T + ref_e = torch.matmul(x_e, w_e).to(torch.bfloat16) + _assert_close(out[start : start + m, :], ref_e, f"expert {e} (m={m})") + print(f" [PASS] BF16 masked experts={num_experts}, max_m={max_m_per_expert}") + + +def test_masked_bf16_mid_m(): + # max_m_per_expert = 128 -> 128x256x64 mid path; masked_m < max exercises masking + _run_masked_bf16( + num_experts=2, max_m_per_expert=128, N=256, K=128, masked_m=[100, 128] + ) + + +# ===================================================================== +# Grouped contiguous GEMM (BF16) +# ===================================================================== + + +def _run_contiguous_bf16(token_nums, N, K): + num_experts = len(token_nums) + m = int(sum(token_nums)) + print(f"[BF16 contiguous] m={m}, N={N}, K={K}, token_nums={token_nums}") + x = torch.randn([m, K], dtype=torch.bfloat16) + w = torch.randn([num_experts, N, K], dtype=torch.bfloat16) + out = torch.zeros([m, N], dtype=torch.bfloat16) + + ids = np.concatenate( + [np.full(c, e, dtype=np.int32) for e, c in enumerate(token_nums)] + ) + expert_ids = torch.tensor(ids, dtype=torch.int32) + + group_contiguous_gemm(x, w, None, None, expert_ids, out, mode="bf16") + + offset = 0 + for e, c in enumerate(token_nums): + x_e = x[offset : offset + c, :].to(torch.float32) + w_e = w[e].to(torch.float32).T + ref_e = torch.matmul(x_e, w_e).to(torch.bfloat16) + _assert_close(out[offset : offset + c, :], ref_e, f"expert {e} (m={c})") + offset += c + print(f" [PASS] BF16 contiguous m={m}, experts={num_experts}") + + +def test_contiguous_bf16_mid_m(): + # Each expert's token count aligned to tile_m=128; m=512 -> 128x256x64 path. + _run_contiguous_bf16(token_nums=[256, 256], N=256, K=128) + + +if __name__ == "__main__": + print("=" * 60) + print("BF16 batch / grouped GEMM tests") + print("=" * 60) + test_batch_bf16_mid_m() + test_batch_bf16_large_m() + test_masked_bf16_mid_m() + test_contiguous_bf16_mid_m() + print("\n" + "=" * 60) + print("All BF16 batch/grouped GEMM tests passed!") + print("=" * 60) From d65e3268b1324c5cb13e42d9a8925c8a609cf7a3 Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 5 Nov 2026 14:14:43 +0800 Subject: [PATCH 02/14] refactor(gemm): take sfa/sfb as std::optional instead of python-side placeholders MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review feedback on the BF16 GEMM commit: the four entry points (DenseGemm / BatchGemm / GroupContiguousGemm / GroupMaskedGemm) now take sfa/sfb as const std::optional& — same convention as bias/alpha in these signatures — and the python wrappers no longer substitute torch.empty(0) placeholders before calling into the extension (pybind maps None to nullopt directly). Quantized branches (w8a8-mxfp8 / w4a4-*) gain an explicit has_value() check with a clear error message; the bf16 branch already ignored sfa/sfb and is unchanged. Verified: tests/test_gemm_bf16.py, tests/test_gemm_bf16_grouped.py all pass, quantized paths with real sfa/sfb unaffected. Co-Authored-By: Claude Code --- csrc/common/cpp_extensions.cc | 25 ++++++++------- csrc/kernel/gemm/batch_gemm.cu | 23 +++++++++----- csrc/kernel/gemm/dense_gemm.cu | 38 ++++++++++++++--------- csrc/kernel/gemm/group_contiguous_gemm.cu | 26 ++++++++++------ csrc/kernel/gemm/group_masked_gemm.cu | 23 +++++++++----- halops/gemm/batch_gemm.py | 5 --- halops/gemm/dense_gemm.py | 5 --- halops/gemm/group_contiguous_gemm.py | 5 --- halops/gemm/group_masked_gemm.py | 5 --- 9 files changed, 84 insertions(+), 71 deletions(-) diff --git a/csrc/common/cpp_extensions.cc b/csrc/common/cpp_extensions.cc index e3c2abe..2cea984 100644 --- a/csrc/common/cpp_extensions.cc +++ b/csrc/common/cpp_extensions.cc @@ -71,7 +71,8 @@ void DecoderAttention( const int mtp_steps, const std::string& cache_quant_type_str); void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, + const std::optional& sfa, + const std::optional& sfb, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, const int sm_count, const std::string& mode, const bool use_pdl, @@ -80,24 +81,26 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, const double situ_beta, const std::optional situ_linear_beta); -void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, - const torch::Tensor& masked_m, torch::Tensor& output, - const std::optional& bias, - const std::optional& alpha, - const int max_m_per_expert, const int sm_count, - const std::string& mode); +void GroupMaskedGemm( + const torch::Tensor& input, const torch::Tensor& weight, + const std::optional& sfa, + const std::optional& sfb, const torch::Tensor& masked_m, + torch::Tensor& output, const std::optional& bias, + const std::optional& alpha, const int max_m_per_expert, + const int sm_count, const std::string& mode); void GroupContiguousGemm(const torch::Tensor& input, - const torch::Tensor& weight, const torch::Tensor& sfa, - const torch::Tensor& sfb, + const torch::Tensor& weight, + const std::optional& sfa, + const std::optional& sfb, const torch::Tensor& expert_ids, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, const int sm_count, const std::string& mode); void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, + const std::optional& sfa, + const std::optional& sfb, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, const int sm_count, const std::string& mode, const EpilogueOp epilogue, diff --git a/csrc/kernel/gemm/batch_gemm.cu b/csrc/kernel/gemm/batch_gemm.cu index 039ef5d..300c0f0 100644 --- a/csrc/kernel/gemm/batch_gemm.cu +++ b/csrc/kernel/gemm/batch_gemm.cu @@ -22,7 +22,8 @@ namespace halops { void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, + const std::optional& sfa, + const std::optional& sfb, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, const int sm_count, const std::string& mode, const EpilogueOp epilogue, @@ -110,6 +111,9 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, KernelConfig>(params, sm, stream); }); } else if (mode == "w8a8-mxfp8") { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "w8a8-mxfp8 batch GEMM requires sfa/sfb scale factors " + "(only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(2); TORCH_CHECK(input.size(2) == k, "input K must match weight K, got input K=", input.size(2), @@ -117,8 +121,8 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); if (bias.has_value()) { params.ptr_c = bias->data_ptr(); } @@ -174,6 +178,9 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, static_cast(epilogue), " for ", mode); } } else { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "W4A4 batch GEMM requires sfa/sfb scale factors " + "(only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(2) * 2; // 2 FP4 per packed byte TORCH_CHECK(input.size(2) == weight.size(2), "packed input K/2 must match packed weight K/2, got ", @@ -181,19 +188,19 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); TORCH_CHECK(!bias.has_value(), "W4A4 batch GEMM does not support bias yet."); const bool mxfp4 = mode == "w4a4-mxfp4"; const int sf_k = k / (mxfp4 ? 32 : 16); - TORCH_CHECK(sfa.size(-1) == sf_k && sfb.size(-1) == sf_k, + TORCH_CHECK(sfa->size(-1) == sf_k && sfb->size(-1) == sf_k, "W4A4 scale-factor shape does not match mode ", mxfp4 ? "'w4a4-mxfp4' (UE8M0 per 32)" : "'w4a4-nvfp4' (UE4M3 per 16)", - " requires SF K = ", sf_k, ", got sfa K=", sfa.size(-1), - " and sfb K=", sfb.size(-1), "."); + " requires SF K = ", sf_k, ", got sfa K=", sfa->size(-1), + " and sfb K=", sfb->size(-1), "."); TORCH_CHECK(!mxfp4 || !alpha.has_value(), "'w4a4-mxfp4' does not take alpha; the per-batch scaling " diff --git a/csrc/kernel/gemm/dense_gemm.cu b/csrc/kernel/gemm/dense_gemm.cu index 674765b..c6651b4 100644 --- a/csrc/kernel/gemm/dense_gemm.cu +++ b/csrc/kernel/gemm/dense_gemm.cu @@ -22,7 +22,8 @@ namespace halops { void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, + const std::optional& sfa, + const std::optional& sfb, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, const int sm_count_arg, const std::string& mode, @@ -277,6 +278,9 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, KernelConfig>(params, sm, stream); }); } else if (mode == "w8a8-mxfp8") { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "w8a8-mxfp8 dense GEMM requires sfa/sfb scale factors " + "(only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(1); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -284,21 +288,21 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); // sfb is the quantizer's uint8 SfAtom weight scale, used as-is: a // 224-wide tile reads it as a run of atoms plus a 32-row rewrite. - TORCH_CHECK(sfb.scalar_type() == torch::kUInt8, + TORCH_CHECK(sfb->scalar_type() == torch::kUInt8, "sfb must be the uint8 SfAtom weight scale that " "group_wise_quant returns"); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfb = sfb->data_ptr(); if (bias.has_value()) { params.ptr_c = bias->data_ptr(); } TORCH_CHECK( - sfa.is_contiguous() && sfa.numel() >= int64_t(m_sf) * (k / 32), + sfa->is_contiguous() && sfa->numel() >= int64_t(m_sf) * (k / 32), "sfa must hold whole 128-row SfAtoms: expected at least ", int64_t(m_sf) * (k / 32), " elements (", m_sf, " x ", k / 32, - ") for M=", m, ", got ", sfa.numel()); + ") for M=", m, ", got ", sfa->numel()); TORCH_CHECK(!bias_tile || m % 256 == 0, "the bias tile has no per-row store predicate yet, so M " "must be a multiple of 256 when bias is given, got ", @@ -330,6 +334,9 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, static_cast(epilogue), " for ", mode); } } else { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "W4A4 dense GEMM requires sfa/sfb scale factors " + "(only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(1) * 2; // 2 FP4 per packed byte TORCH_CHECK( input.size(1) == weight.size(1), @@ -338,8 +345,8 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); TORCH_CHECK(!bias.has_value(), "W4A4 mode does not support bias yet."); const bool mxfp4 = mode == "w4a4-mxfp4"; @@ -349,16 +356,17 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_alpha = alpha.has_value() ? alpha->data_ptr() : nullptr; const int sf_k = k / (mxfp4 ? 32 : 16); - TORCH_CHECK(sfa.size(-1) == sf_k && sfb.size(-1) == sf_k, + TORCH_CHECK(sfa->size(-1) == sf_k && sfb->size(-1) == sf_k, "W4A4 scale-factor shape does not match mode ", mxfp4 ? "'w4a4-mxfp4' (UE8M0 per 32)" : "'w4a4-nvfp4' (UE4M3 per 16)", - " requires SF K = ", sf_k, ", got sfa K=", sfa.size(-1), - " and sfb K=", sfb.size(-1), "."); - TORCH_CHECK(sfa.is_contiguous() && sfa.numel() >= int64_t(m_sf) * sf_k, - "sfa must hold whole 128-row SfAtoms: expected at least ", - int64_t(m_sf) * sf_k, " elements (", m_sf, " x ", sf_k, - ") for M=", m, ", got ", sfa.numel()); + " requires SF K = ", sf_k, ", got sfa K=", sfa->size(-1), + " and sfb K=", sfb->size(-1), "."); + TORCH_CHECK( + sfa->is_contiguous() && sfa->numel() >= int64_t(m_sf) * sf_k, + "sfa must hold whole 128-row SfAtoms: expected at least ", + int64_t(m_sf) * sf_k, " elements (", m_sf, " x ", sf_k, + ") for M=", m, ", got ", sfa->numel()); TORCH_CHECK(!mxfp4 || !alpha.has_value(), "'w4a4-mxfp4' does not take alpha; the per-batch scaling " "factor is only used by 'w4a4-nvfp4'."); diff --git a/csrc/kernel/gemm/group_contiguous_gemm.cu b/csrc/kernel/gemm/group_contiguous_gemm.cu index f993138..5e4b756 100644 --- a/csrc/kernel/gemm/group_contiguous_gemm.cu +++ b/csrc/kernel/gemm/group_contiguous_gemm.cu @@ -22,8 +22,9 @@ namespace halops { void GroupContiguousGemm(const torch::Tensor& input, - const torch::Tensor& weight, const torch::Tensor& sfa, - const torch::Tensor& sfb, + const torch::Tensor& weight, + const std::optional& sfa, + const std::optional& sfb, const torch::Tensor& expert_ids, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, @@ -104,6 +105,10 @@ void GroupContiguousGemm(const torch::Tensor& input, KernelConfig>(params, sm, stream); }); } else if (mode == "w8a8-mxfp8") { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "w8a8-mxfp8 contiguous grouped GEMM requires sfa/sfb " + "scale factors (only mode='bf16' accepts sfa=None, " + "sfb=None)"); const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -111,8 +116,8 @@ void GroupContiguousGemm(const torch::Tensor& input, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); if (bias.has_value()) { params.ptr_c = bias->data_ptr(); } @@ -156,6 +161,9 @@ void GroupContiguousGemm(const torch::Tensor& input, .has_bias = false}, stream); } else { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "W4A4 contiguous grouped GEMM requires sfa/sfb scale " + "factors (only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(2) * 2; // 2 FP4 per packed byte TORCH_CHECK( input.size(1) == weight.size(2), @@ -164,18 +172,18 @@ void GroupContiguousGemm(const torch::Tensor& input, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); TORCH_CHECK(!bias.has_value(), "W4A4 mode does not support bias yet."); const bool mxfp4 = mode == "w4a4-mxfp4"; const int sf_k = k / (mxfp4 ? 32 : 16); - TORCH_CHECK(sfa.size(-1) == sf_k && sfb.size(-1) == sf_k, + TORCH_CHECK(sfa->size(-1) == sf_k && sfb->size(-1) == sf_k, "W4A4 scale-factor shape does not match mode ", mxfp4 ? "'w4a4-mxfp4' (UE8M0 per 32)" : "'w4a4-nvfp4' (UE4M3 per 16)", - " requires SF K = ", sf_k, ", got sfa K=", sfa.size(-1), - " and sfb K=", sfb.size(-1), "."); + " requires SF K = ", sf_k, ", got sfa K=", sfa->size(-1), + " and sfb K=", sfb->size(-1), "."); TORCH_CHECK(!mxfp4 || !alpha.has_value(), "'w4a4-mxfp4' does not take alpha; the per-expert scaling " diff --git a/csrc/kernel/gemm/group_masked_gemm.cu b/csrc/kernel/gemm/group_masked_gemm.cu index c003f82..33539b2 100644 --- a/csrc/kernel/gemm/group_masked_gemm.cu +++ b/csrc/kernel/gemm/group_masked_gemm.cu @@ -22,7 +22,8 @@ namespace halops { void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, + const std::optional& sfa, + const std::optional& sfb, const torch::Tensor& masked_m, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, @@ -114,6 +115,9 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, KernelConfig>(params, sm, stream); }); } else if (mode == "w8a8-mxfp8") { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "w8a8-mxfp8 masked grouped GEMM requires sfa/sfb scale " + "factors (only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -121,8 +125,8 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); if (bias.has_value()) { params.ptr_c = bias->data_ptr(); } @@ -164,6 +168,9 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, .has_bias = false}, stream); } else { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "W4A4 masked grouped GEMM requires sfa/sfb scale factors " + "(only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(2) * 2; // 2 FP4 per packed byte TORCH_CHECK( input.size(1) == weight.size(2), @@ -172,18 +179,18 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); TORCH_CHECK(!bias.has_value(), "W4A4 mode does not support bias yet."); const bool mxfp4 = mode == "w4a4-mxfp4"; const int sf_k = k / (mxfp4 ? 32 : 16); - TORCH_CHECK(sfa.size(-1) == sf_k && sfb.size(-1) == sf_k, + TORCH_CHECK(sfa->size(-1) == sf_k && sfb->size(-1) == sf_k, "W4A4 scale-factor shape does not match mode ", mxfp4 ? "'w4a4-mxfp4' (UE8M0 per 32)" : "'w4a4-nvfp4' (UE4M3 per 16)", - " requires SF K = ", sf_k, ", got sfa K=", sfa.size(-1), - " and sfb K=", sfb.size(-1), "."); + " requires SF K = ", sf_k, ", got sfa K=", sfa->size(-1), + " and sfb K=", sfb->size(-1), "."); TORCH_CHECK(!mxfp4 || !alpha.has_value(), "'w4a4-mxfp4' does not take alpha; the per-expert scaling " diff --git a/halops/gemm/batch_gemm.py b/halops/gemm/batch_gemm.py index b0e289a..70fac1e 100644 --- a/halops/gemm/batch_gemm.py +++ b/halops/gemm/batch_gemm.py @@ -102,11 +102,6 @@ def batch_gemm( >>> out = torch.empty(m, b * n, dtype=torch.bfloat16, device="cuda") >>> batch_gemm(x, w, sfa, sfb, out, mode="w8a8-mxfp8") """ - if sfa is None: - sfa = torch.empty(0, dtype=torch.uint8, device=input.device) - if sfb is None: - sfb = torch.empty(0, dtype=torch.uint8, device=input.device) - halops_kernel.batch_gemm( input, weight, diff --git a/halops/gemm/dense_gemm.py b/halops/gemm/dense_gemm.py index a82b250..7b82081 100644 --- a/halops/gemm/dense_gemm.py +++ b/halops/gemm/dense_gemm.py @@ -118,11 +118,6 @@ def dense_gemm( >>> out = torch.empty(m, n, dtype=torch.bfloat16, device="cuda") >>> dense_gemm(x, w, sfa, sfb, out, mode="w8a8-mxfp8") """ - if sfa is None: - sfa = torch.empty(0, dtype=torch.uint8, device=input.device) - if sfb is None: - sfb = torch.empty(0, dtype=torch.uint8, device=input.device) - halops_kernel.dense_gemm( input, weight, diff --git a/halops/gemm/group_contiguous_gemm.py b/halops/gemm/group_contiguous_gemm.py index 7defd0f..6c8d515 100644 --- a/halops/gemm/group_contiguous_gemm.py +++ b/halops/gemm/group_contiguous_gemm.py @@ -96,11 +96,6 @@ def group_contiguous_gemm( >>> out = torch.empty(m, n, dtype=torch.bfloat16, device="cuda") >>> group_contiguous_gemm(x, w, sfa, sfb, expert_ids, out, mode="w8a8-mxfp8") """ - if sfa is None: - sfa = torch.empty(0, dtype=torch.uint8, device=input.device) - if sfb is None: - sfb = torch.empty(0, dtype=torch.uint8, device=input.device) - halops_kernel.group_contiguous_gemm( input, weight, diff --git a/halops/gemm/group_masked_gemm.py b/halops/gemm/group_masked_gemm.py index e25d2ea..66d82cb 100644 --- a/halops/gemm/group_masked_gemm.py +++ b/halops/gemm/group_masked_gemm.py @@ -99,11 +99,6 @@ def group_masked_gemm( ... max_m_per_expert=max_m_per_expert, mode="w8a8-mxfp8", ... ) """ - if sfa is None: - sfa = torch.empty(0, dtype=torch.uint8, device=input.device) - if sfb is None: - sfb = torch.empty(0, dtype=torch.uint8, device=input.device) - halops_kernel.group_masked_gemm( input, weight, From bd4fb8c5a12e4b72393223f6b30c19a71c52548f Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 5 Nov 2026 17:16:36 +0800 Subject: [PATCH 03/14] refactor(gemm): fold BF16 dispatch into gemm_tile.h / gemm_dispatch.h Address review feedback on bf16_cfgs.h: - Drop every HALOPS_* tile-selection env knob (EnvIs / EnvNot0 / EnvIntOr / EnvInt64Or and ~30 switches) and fix each to the shipped default, so behaviour is unchanged; the cluster4 / stage-override / tile-k32 debug arms are gone with them. Also removes the HALOPS_FORCE_CFG hatch from dense_gemm.cu. - Rename the cryptic helpers: DeepProloguePays -> UseDeepPipeline, ThinMNoSwapOk -> SkipSwapForThinM, PacksTailTighter -> FillsLastWaveBetter, PreferFinePairN -> UseNarrowPairTile, PairDeepCtaCount -> Count128x64PairCtas. - Split the ~500-line SelectBF16Cfg ladder into per-region helpers (SelectLargeMTile / SelectMidMTile / SelectThinMTile / SelectSwapABTile, plus Pick128xNWidth / SelectPair256xNTile), preserving every decision. - Represent BF16 tiles as TileSpec tables next to kFp8Tiles/kFp4Tiles and derive the kernel configs through MakeTile (TileSpec gains epi_warp_groups / force_ntail); selectors and launch helpers move into gemm_dispatch.cuh; bf16_cfgs.h is deleted. The generic launcher now takes a tile-table policy, so FP8/FP4 use it unchanged. - Prune 10 BF16 tiles that only reachable through the removed env switches (2x2CTA cluster family, 128x32 K32/P4/P6, 64x64 P12/P14, 64x32 P14). - static_assert field locks replace the old GemmTile alias assertions. Verified: tests/test_gemm_bf16.py, test_gemm_bf16_grouped.py and the quantized dense/batch/contiguous/masked suites pass; ci dense_bf16 and batch_bf16 baselines pass within the 5% threshold (no dispatch drift). Co-Authored-By: Claude Code --- csrc/kernel/gemm/batch_gemm.cu | 29 +- csrc/kernel/gemm/bf16_cfgs.h | 1015 --------------------- csrc/kernel/gemm/dense_gemm.cu | 184 +--- csrc/kernel/gemm/gemm_dispatch.cuh | 649 ++++++++++++- csrc/kernel/gemm/gemm_tile.cuh | 492 +++++----- csrc/kernel/gemm/group_contiguous_gemm.cu | 36 +- csrc/kernel/gemm/group_masked_gemm.cu | 37 +- 7 files changed, 957 insertions(+), 1485 deletions(-) delete mode 100644 csrc/kernel/gemm/bf16_cfgs.h diff --git a/csrc/kernel/gemm/batch_gemm.cu b/csrc/kernel/gemm/batch_gemm.cu index 300c0f0..3553f2e 100644 --- a/csrc/kernel/gemm/batch_gemm.cu +++ b/csrc/kernel/gemm/batch_gemm.cu @@ -15,7 +15,6 @@ #include #include -#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -23,8 +22,8 @@ namespace halops { void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, const std::optional& sfa, - const std::optional& sfb, - torch::Tensor& output, const std::optional& bias, + const std::optional& sfb, torch::Tensor& output, + const std::optional& bias, const std::optional& alpha, const int sm_count, const std::string& mode, const EpilogueOp epilogue, const std::optional& output_sf, @@ -70,13 +69,8 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.use_pdl = use_pdl; if (mode == "bf16") { - using TypeA = cutlass::bfloat16_t; - using TypeB = cutlass::bfloat16_t; - using TypeC = cutlass::bfloat16_t; - using TypeD = cutlass::bfloat16_t; - using TypeSF = cutlass::float_ue8m0_t; // placeholder, unused - using TypeAccumulate = float; - + // Native BF16: sfa/sfb/bias/alpha are ignored; dispatch and launch + // live in gemm_dispatch.cuh (bf16::LaunchBatch). const int k = weight.size(2); TORCH_CHECK(input.size(2) == k, "input K must match weight K, got input K=", input.size(2), @@ -96,20 +90,7 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - - const int cfg = bf16_dispatch::SelectBF16BatchCfg(m, n, k); - TORCH_CHECK(cfg >= 0, "bf16 batch GEMM: unsupported shape B=", batches, - " M=", m, " N=", n, " K=", k, - ". Need one of: (M%256==0 && N%256==0), " - "(M%128==0 && N%256==0), or (M%64==0 && N%128==0)."); - bf16_dispatch::CheckBF16CfgShape( - "bf16 batch GEMM", bf16_dispatch::kBF16BatchCfgs[cfg], m, n, k); - bf16_dispatch::DispatchBF16SmallCfg( - cfg, "bf16 batch", [&]() { - gemm_impl(params, sm, stream); - }); + bf16::LaunchBatch(params, sm, stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 batch GEMM requires sfa/sfb scale factors " diff --git a/csrc/kernel/gemm/bf16_cfgs.h b/csrc/kernel/gemm/bf16_cfgs.h deleted file mode 100644 index e0a2066..0000000 --- a/csrc/kernel/gemm/bf16_cfgs.h +++ /dev/null @@ -1,1015 +0,0 @@ -// Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// =========================================================================== -// BF16 dense/grouped/batch dispatch: the shape-aware ladder moved verbatim -// from the DenseGemm/GroupContiguousGemm/GroupMaskedGemm/BatchGemm host -// functions. Unlike the W8A8 cost model (SelectDenseCfg above), the BF16 -// ladder is rule-based (pair-UMMA CTA bands, stream-K, k-tile depth gates, -// wave-fill judgements) -- the same shape as SelectW4A4Cfg, just longer. -// Selectors return a catalog id; DispatchBF16*Cfg maps ids to instantiations. -// =========================================================================== - -#pragma once - -#include -#include -#include -#include - -#include "kernel/gemm/gemm_tile.cuh" -#include "kernel/gemm/gemm_utils.h" - -namespace halops { -namespace bf16_dispatch { - -// --------------------------------------------------------------------------- -// Shared helpers (verbatim from the old dense_gemm.cu anonymous namespace). -// --------------------------------------------------------------------------- - -constexpr int64_t kPairDeepMinCtas = 40; -constexpr int64_t kPairDeepMaxCtas = 152; - -constexpr int64_t CeilDiv(int64_t x, int64_t d) { return (x + d - 1) / d; } - -// KBlockK of every BF16 config below. -constexpr int64_t kBF16BlockK = 64; - -// Deep-prologue configs (14/18 stages) only help with at least this many -// K-tiles. -constexpr int64_t kDeepPrologueMinKTiles = 32; - -inline bool DeepProloguePays(int k) { - return k / kBF16BlockK >= kDeepPrologueMinKTiles; -} - -inline int64_t PairDeepCtaCount(int m, int n) { - return 2 * CeilDiv(m, 128) * CeilDiv(n, 64); -} - -inline void CheckPairDeepCtaBand(int m, int n, int cluster4_arm) { - // HALOPS_PAIR_UNSAFE=1 lifts the guard (debugging only). - static const bool unsafe_ok = [] { - const char* e = std::getenv("HALOPS_PAIR_UNSAFE"); - return e != nullptr && e[0] == '1'; - }(); - if (unsafe_ok) { - return; - } - const int64_t ctas = PairDeepCtaCount(m, n); - TORCH_CHECK(ctas >= kPairDeepMinCtas && ctas <= kPairDeepMaxCtas, - "HALOPS_CLUSTER4=", cluster4_arm, - " selects the 2SM/KBlockM=128 pair-UMMA family, which is still " - "numerically WRONG outside a CTA count of [", - kPairDeepMinCtas, ", ", kPairDeepMaxCtas, - "]. This shape (m=", m, ", n=", n, ") gives ", ctas, - " CTAs; refusing rather than " - "returning silently wrong results."); -} - -// For m < 128: use a non-SwapAB KBlockM=64 tile when even SwapAB's smallest -// tile leaves SMs idle. HALOPS_M64_NOSWAP=0 always uses SwapAB. -inline bool ThinMNoSwapOk(int m, int n, int k, int sm_count) { - static const bool disabled = [] { - const char* e = std::getenv("HALOPS_M64_NOSWAP"); - return e != nullptr && e[0] == '0'; - }(); - if (disabled) { - return false; - } - if (m % 64 != 0 || k % 64 != 0) { - return false; - } - const int target = ResolveSmCount(sm_count); - const int64_t nt32 = CeilDiv(n, 32); - const int64_t mt = CeilDiv(m, 64); - const bool narrow_ok = (n % 32 == 0) && (nt32 * mt <= target); - const bool square_ok = (n % 64 == 0); - if (!narrow_ok && !square_ok) { - return false; - } - const int64_t swapab_tiles = CeilDiv(n, 128) * CeilDiv(m, 32); - return swapab_tiles < target; -} - -// Above this many K-tiles keep 256x256: 256x128 re-reads A twice as often, -// which outweighs any wave-packing gain. -constexpr int64_t kPairFineNMaxKTiles = 64; - -// Minimum K-tiles for the deep-prologue mid-M configs (64x96 P11, 128x64 pair -// P18). -constexpr int64_t kMidMDeepPrologueMinKTiles = 54; - -// True if fine_ctas keeps a larger fraction of SMs busy than coarse_ctas, -// where busy fraction = ctas / (target * number_of_waves). -inline bool PacksTailTighter(int64_t coarse_ctas, int64_t fine_ctas, - int64_t target) { - const int64_t coarse_waves = (coarse_ctas + target - 1) / target; - const int64_t fine_waves = (fine_ctas + target - 1) / target; - return fine_ctas * coarse_waves > coarse_ctas * fine_waves; -} - -// HALOPS_PAIR_FINE_N=0 disables PreferFinePairN at both call sites. -inline bool PairFineNDisabled() { - static const bool disabled = [] { - const char* e = std::getenv("HALOPS_PAIR_FINE_N"); - return e != nullptr && e[0] == '0'; - }(); - return disabled; -} - -// Use 256x128 instead of 256x256 for the pair-UMMA tile when K is short and -// 256x128 keeps more SMs busy; beyond 4 waves the gain is negligible. -inline bool PreferFinePairN(int n, int k, int64_t coarse_ctas, - int64_t fine_ctas, int64_t target) { - return (n % 128 == 0) && (k / 64 <= kPairFineNMaxKTiles) && - (coarse_ctas <= 4 * target) && - PacksTailTighter(coarse_ctas, fine_ctas, target); -} - -// ---- Small-N tiles (N <= 128) ---------------------------------------------- -// N fits in a single tile, so all CTAs must come from splitting M. Pick the -// largest tile whose CTA count is within (0.5, 1.0] of one wave. -// HALOPS_SMALL_N=0 disables this. -inline bool SmallNLadderDisabled() { - static const bool disabled = [] { - const char* e = std::getenv("HALOPS_SMALL_N"); - return e != nullptr && e[0] == '0'; - }(); - return disabled; -} - -enum class SmallNTile { - kNone, - kPairM256N128, - kM64N128, - kPairM256N64, - kM64N64, -}; - -constexpr int64_t kSmallNMaxN = 128; -constexpr int64_t kSmallNAlignN = 64; - -inline bool FillsOneWave(int64_t ctas, int64_t target) { - return ctas <= target && 2 * ctas > target; -} - -struct SmallNRung { - SmallNTile tile; - int64_t block_m; - int64_t block_n; - int64_t ctas_per_cluster; -}; - -inline SmallNTile PickSmallNTile(int m, int n, int64_t target) { - if (SmallNLadderDisabled() || n > kSmallNMaxN || n % kSmallNAlignN != 0) { - return SmallNTile::kNone; - } - static constexpr SmallNRung kRungs[] = { - {SmallNTile::kPairM256N128, 256, 128, 2}, - {SmallNTile::kM64N128, 64, 128, 1}, - {SmallNTile::kPairM256N64, 256, 64, 2}, - {SmallNTile::kM64N64, 64, 64, 1}, - }; - for (const SmallNRung& r : kRungs) { - const int64_t ctas = - r.ctas_per_cluster * CeilDiv(m, r.block_m) * CeilDiv(n, r.block_n); - if (FillsOneWave(ctas, target)) { - return r.tile; - } - } - // No tile fits; use the regular large-M dispatch. - return SmallNTile::kNone; -} - -// --------------------------------------------------------------------------- -// Environment-variable knobs, read once per process (static locals). -// --------------------------------------------------------------------------- - -inline bool EnvIs(const char* name, const char* value) { - const char* e = std::getenv(name); - return e != nullptr && e[0] == value[0]; -} - -inline bool EnvNot0(const char* name) { - const char* e = std::getenv(name); - return e == nullptr || e[0] != '0'; -} - -inline int EnvIntOr(const char* name, int fallback) { - const char* e = std::getenv(name); - return e != nullptr ? atoi(e) : fallback; -} - -inline int64_t EnvInt64Or(const char* name, int64_t fallback) { - const char* e = std::getenv(name); - return e != nullptr ? static_cast(atoll(e)) : fallback; -} - -// --------------------------------------------------------------------------- -// Dense (Naive) catalog. Order defines the id; ids are only meaningful -// together with DispatchBF16Cfg below (both index the same tuple). -// --------------------------------------------------------------------------- - -using BF16Tiles = - cute::tuple; // 34 -constexpr int kBF16CfgCount = static_cast(cute::tuple_size_v); - -// Index of a tile in the catalog (dispatch names tiles by type; reordering -// the list cannot silently re-point an id). -template -constexpr int BF16TileIndex() { - if constexpr (I < kBF16CfgCount) { - if constexpr (cute::is_same, - T>::value) { - return I; - } else { - return BF16TileIndex(); - } - } else { - static_assert(I < 0, "tile is not in BF16Tiles"); - return -1; - } -} - -// Shape descriptor for host-side divisibility checks after selection. -struct BF16CfgDesc { - int bm; // KBlockM (for SwapAB: the weight M) - int bn; // KBlockN (for SwapAB: the activation extent) - int bk; // KBlockK - bool swap; // SwapAB - bool ntail; // KForceEpiNPredicate: N only needs % 64 (or % 32 for - // non-power-of-2 KBlockN) -}; - -template -constexpr BF16CfgDesc MakeBF16Desc() { - return {T::KBlockM, T::KBlockN, T::KBlockK, T::SwapAB, - T::KForceEpiNPredicate}; -} - -template -constexpr std::array MakeBF16Table( - std::index_sequence) { - return {{MakeBF16Desc>()...}}; -} - -constexpr auto kBF16Cfgs = - MakeBF16Table(std::make_index_sequence{}); - -// --------------------------------------------------------------------------- -// SelectBF16Cfg: the dense ladder, moved verbatim from dense_gemm.cu. -// Returns a BF16Tiles catalog id or -1 when no rung supports the shape. -// The caller validates divisibility against kBF16Cfgs[id] and launches via -// DispatchBF16Cfg. -// --------------------------------------------------------------------------- - -namespace dense { - -using bf16_dispatch::CeilDiv; -using bf16_dispatch::CheckPairDeepCtaBand; -using bf16_dispatch::DeepProloguePays; -using bf16_dispatch::EnvInt64Or; -using bf16_dispatch::EnvIntOr; -using bf16_dispatch::EnvIs; -using bf16_dispatch::EnvNot0; -using bf16_dispatch::kBF16BlockK; -using bf16_dispatch::kMidMDeepPrologueMinKTiles; -using bf16_dispatch::PacksTailTighter; -using bf16_dispatch::PairDeepCtaCount; -using bf16_dispatch::PairFineNDisabled; -using bf16_dispatch::PickSmallNTile; -using bf16_dispatch::PreferFinePairN; -using bf16_dispatch::SmallNTile; -using bf16_dispatch::ThinMNoSwapOk; - -inline int SelectBF16Cfg(int m, int n, int k, int sm_count) { - if (m >= 4096) { - // Large-M: 256x256 pair tile by default, or 256x128 (deeper - // pipeline) when PreferFinePairN says so. If n % 256 != 0, fall - // back to 256x128, then _Ntail / 256x64; n % 64 != 0 is rejected. - const int target_sm = ResolveSmCount(sm_count); - switch (PickSmallNTile(m, n, target_sm)) { - case SmallNTile::kM64N128: - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA>(); - case SmallNTile::kM64N64: { - // HALOPS_SMALLN_1WG_DEEP=0 restores 2WG/10 stages. - static const bool smalln_1wg_deep = - EnvNot0("HALOPS_SMALLN_1WG_DEEP"); - if (smalln_1wg_deep && DeepProloguePays(k)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA>(); - } - case SmallNTile::kPairM256N64: - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA>(); - // Handled by the default dispatch below. - case SmallNTile::kPairM256N128: - case SmallNTile::kNone: - break; - } - const int64_t tiles_256 = CeilDiv(m, 256) * CeilDiv(n, 256); - const int64_t mt_256 = CeilDiv(m, 256); - const bool square_like = - PairFineNDisabled() - ? ((n % 128 == 0) && (tiles_256 <= 2 * target_sm)) - : PreferFinePairN(n, k, 2 * tiles_256, - 2 * mt_256 * CeilDiv(n, 128), target_sm); - // HALOPS_LARGEM_DEEP=0 restores the shallower P6/P8 configs. - static const bool largem_deep = EnvNot0("HALOPS_LARGEM_DEEP"); - if (square_like) { - return largem_deep - ? bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9>() - : bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA>(); - } - if (n % 256 == 0) { - return largem_deep - ? bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA_P7>() - : bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA>(); - } - if (n % 128 == 0) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA>(); - } - // n % 128 != 0 (e.g. 1600): 128-wide _Ntail tile, which masks - // the store of the partial last tile. HALOPS_LARGEM_NTAIL=0 - // uses 256x64 instead. - static const bool largem_ntail_disabled = - EnvIs("HALOPS_LARGEM_NTAIL", "0"); - if (!largem_ntail_disabled && (n % 64 == 0)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA>(); - } - - if (m >= 128) { - // The narrowest mid-M tile is 128x32, so only n % 32 is needed. - if (m % 128 != 0 || n % 32 != 0 || k % 64 != 0) { - return -1; - } - - // HALOPS_CLUSTER4=1..5 forces a clustered 128x64 pair variant - // (debugging only; checked against the trusted CTA band). - static const int cluster4 = EnvIntOr("HALOPS_CLUSTER4", 0); - if (cluster4 != 0 && (m % 128 == 0) && (n % 128 == 0) && - (k % 64 == 0)) { - CheckPairDeepCtaBand(m, n, cluster4); - switch (cluster4) { - case 1: - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA>(); - case 3: - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P16>(); - case 4: - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18>(); - case 5: - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18>(); - default: - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_2x1CTA>(); - } - } - - // ---- KBlockM=64 tiles (64x64 / 64x32) -------------------------- - // Smaller tiles add CTAs, but with no multicast each extra N-tile - // reloads A. Use them only if the grid fits one wave and the A - // reload volume k_tiles * n_tiles is within rereads_cap. - // HALOPS_TILE_M64=0 disables them. - static const bool m64_disabled = EnvIs("HALOPS_TILE_M64", "0"); - if (!m64_disabled && (m % 64 == 0) && (n % 64 == 0) && (k % 64 == 0)) { - const int sm = ResolveSmCount(sm_count); - const int64_t tiles64 = CeilDiv(m, 64) * CeilDiv(n, 64); - const int64_t rereads = (k / kBF16BlockK) * CeilDiv(n, 64); - // HALOPS_REREADS_CAP= overrides the re-read cap. - static const int64_t rereads_cap = - EnvInt64Or("HALOPS_REREADS_CAP", 2048); - // HALOPS_FORCE_M64_N32=1 uses 64x32 regardless of both - // limits. - static const bool n32_force = EnvIs("HALOPS_FORCE_M64_N32", "1"); - if (n32_force || (tiles64 <= sm && rereads <= rereads_cap)) { - // 1-epilogue-WG configs: required for 64x32 (KEpiComputeN - // must be >= 32) and free of the inter-WG barrier. Use - // 64x32 if twice the 64x64 tile count still fits one wave, - // else 64x64. HALOPS_M64_1WG=0 uses the 2WG 64x64. - static const bool wg1_disabled = EnvIs("HALOPS_M64_1WG", "0"); - if (!wg1_disabled) { - if ((n32_force || 2 * tiles64 <= sm) && (n % 32 == 0)) { - // HALOPS_N32_STAGES=10|14|18 forces the stage - // count. - static const int n32_stages = - EnvIntOr("HALOPS_N32_STAGES", 0); - const bool deep = n32_stages == 0 ? DeepProloguePays(k) - : n32_stages == 18; - if (n32_stages == 14) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P14_1CTA>(); - } - if (deep) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_1CTA>(); - } - // HALOPS_M64_1WG_DEEP=0 restores 10 stages. - static const bool m64_1wg_deep = - EnvNot0("HALOPS_M64_1WG_DEEP"); - if (m64_1wg_deep && DeepProloguePays(k)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA>(); - } - // HALOPS_M64_STAGES=12|14 uses a deeper 2WG 64x64. - static const int m64_stages = EnvIntOr("HALOPS_M64_STAGES", 0); - if (m64_stages == 12) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_P12_1CTA>(); - } - if (m64_stages == 14) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_P14_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA>(); - } - } - - // ---- 128xN tiles ------------------------------------------------ - // Halve N (256 -> 128 -> 64 -> 32) while the current tile leaves - // SMs idle. - const int target = ResolveSmCount(sm_count); - auto tiles = [&](int tm, int tn) { - return ((m + tm - 1) / tm) * ((n + tn - 1) / tn); - }; - // HALOPS_DISABLE_TILE_N32=1 stops at 128x64. - static const bool n32_disabled = EnvIs("HALOPS_DISABLE_TILE_N32", "1"); - // pick: 0=128x256, 1=128x128, 2=128x64, 3=128x32. - int pick; - if (n % 256 == 0) { - pick = 0; - } else if (n % 128 == 0) { - pick = 1; - } else if (n % 64 == 0) { - pick = 2; - } else { - pick = 3; - } - // Keep 128x256 if it already fills half a wave and 128x128 would - // spill into a second wave. - const bool overshoots_128 = - m > 128 && tiles(128, 128) > target && 2 * tiles(128, 256) > target; - if (pick == 0 && tiles(128, 256) < target && (n % 128 == 0) && - !overshoots_128) { - pick = 1; // 128x128 - } - if (pick == 1 && tiles(128, 128) < target && (n % 64 == 0)) { - pick = 2; // 128x64 - } - if (pick == 2 && !n32_disabled && tiles(128, 64) < target && - (n % 32 == 0)) { - pick = 3; // 128x32 - } - - // ---- 256xN pair-UMMA tiles (m % 256 == 0) ---------------------- - // Same CTA count as 128xN, but B is loaded half as often. Used - // only if: - // 1) k_tiles >= 3 * KPrologueStages, or the grid is >= 1 wave; - // 2) for 256x64, the grid is >= 0.8 wave. - // HALOPS_MIDM_PAIR=0 disables them. - static const bool midm_pair = EnvNot0("HALOPS_MIDM_PAIR"); - if (midm_pair && (m % 256 == 0) && (n % 64 == 0) && (k % 64 == 0)) { - auto pair_ctas = [&](int64_t tn) { - return static_cast(m / 256) * ((n + tn - 1) / tn) * 2; - }; - // Halve N only while the grid is under one wave, and never - // from >= half a wave into more than one wave. - auto step_ok = [&](int64_t coarse, int64_t fine) { - return pair_ctas(coarse) < target && - !(pair_ctas(fine) > target && - 2 * pair_ctas(coarse) > target); - }; - int pair_tn = (n % 256 == 0) ? 256 : ((n % 128 == 0) ? 128 : 64); - // n % 128 != 0 (e.g. 1600): use the 128-wide _Ntail tile - // instead of 64 if it fills at least half a wave. - // HALOPS_MIDM_NTAIL=0 disables it. - static const bool midm_ntail = EnvNot0("HALOPS_MIDM_NTAIL"); - bool pair_n_tail = false; - if (midm_ntail && pair_tn == 64 && (n % 128 != 0) && - 2 * pair_ctas(128) >= target) { - pair_tn = 128; - pair_n_tail = true; - } - // Also use 128 when PreferFinePairN says so (multi-wave). - if (pair_tn == 256 && (n % 128 == 0) && - (step_ok(256, 128) || - (!PairFineNDisabled() && - PreferFinePairN(n, k, pair_ctas(256), pair_ctas(128), - target)))) { - pair_tn = 128; - } - // Use 192 if it fits one wave and keeps more SMs busy than - // both 256 and 128. HALOPS_MIDM_PAIR192=0 disables it. - static const bool midm_pair192 = EnvNot0("HALOPS_MIDM_PAIR192"); - if (midm_pair192 && pair_tn != 64 && (n % 32 == 0) && - pair_ctas(192) <= target && - PacksTailTighter(pair_ctas(256), pair_ctas(192), target) && - PacksTailTighter(pair_ctas(128), pair_ctas(192), target)) { - pair_tn = 192; - pair_n_tail = false; - } - if (!pair_n_tail && pair_tn == 128 && (n % 64 == 0) && - step_ok(128, 64)) { - pair_tn = 64; - } - const int64_t pair_cta_count = pair_ctas(pair_tn); - const int64_t pair_k_tiles = k / 64; - const int pair_stages = - (pair_tn == 256) - ? GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA:: - KPrologueStages - : ((pair_tn == 192) - ? GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA:: - KPrologueStages - : ((pair_tn == 128) - ? GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA:: - KPrologueStages - : GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA:: - KPrologueStages)); - const bool amortizes_prologue = - pair_k_tiles >= 3 * pair_stages || pair_cta_count >= target; - const bool narrow_arm_fills = - pair_tn != 64 || 5 * pair_cta_count >= 4 * target; - // If n % 128 != 0 forced 256x64 and it spills past one wave, - // skip the pair tiles and let 64x96 / 64x224 below handle it. - const int64_t narrow_ctas96 = CeilDiv(m, 64) * CeilDiv(n, 96); - const int64_t narrow_ctas224 = CeilDiv(m, 64) * CeilDiv(n, 224); - const bool ninety_six_legal = - (m % 64 == 0) && (n % 32 == 0) && - (k / kBF16BlockK) >= kMidMDeepPrologueMinKTiles; - const bool two_two_four_legal = (m % 64 == 0) && (n % 32 == 0); - const bool narrow_arm_overshoots = - pair_tn == 64 && pair_cta_count > target && - two_two_four_legal && - (!ninety_six_legal || - PacksTailTighter(narrow_ctas224, narrow_ctas96, target)); - if (amortizes_prologue && narrow_arm_fills && - !narrow_arm_overshoots) { - if (pair_tn == 256) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA>(); - } - if (pair_tn == 192) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA>(); - } - if (pair_tn == 128) { - // HALOPS_MIDM_PAIR_DEEP=0 restores P8. - static const bool midm_pair_deep = - EnvNot0("HALOPS_MIDM_PAIR_DEEP"); - if (pair_n_tail) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9>(); - } - // With <= 32 K-tiles, 128x64x64_1CTA (same CTA count) is - // faster than 256x64 pair. HALOPS_MIDM_PAIR64_1CTA=0 - // disables it. - static const bool midm_pair64_1cta = - EnvNot0("HALOPS_MIDM_PAIR64_1CTA"); - if (midm_pair64_1cta && pair_k_tiles <= 32) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA>(); - } - } - - // If the 128xN tile spills past one wave, use 64x128 when that - // fits in one wave. HALOPS_DISABLE_WAVE64=1 disables it; - // HALOPS_WAVE64_ANYCTA=1 drops the one-wave condition. - static const bool wave64_disabled = EnvIs("HALOPS_DISABLE_WAVE64", "1"); - static const bool wave64_anycta = EnvIs("HALOPS_WAVE64_ANYCTA", "1"); - const int64_t pick_tn = - pick == 0 ? 256 : (pick == 1 ? 128 : (pick == 2 ? 64 : 32)); - // ---- 64x96 / 64x224 tiles -------------------------------------- - // Power-of-2 N widths can miss one wave entirely (n=7168: 112 or - // 224 CTAs on 152 SMs); 96/224 land in between. - // HALOPS_DISABLE_TILE96 / _TILE224 disable them. - static const bool tile96_disabled = EnvIs("HALOPS_DISABLE_TILE96", "1"); - static const bool tile224_disabled = - EnvIs("HALOPS_DISABLE_TILE224", "1"); - auto ctas_at = [&](int64_t tn) { - return CeilDiv(m, 64) * CeilDiv(n, tn); - }; - const int64_t ctas96 = ctas_at(96); - const int64_t ctas224 = ctas_at(224); - const int64_t incumbent_ctas = - (n % 128 == 0 && tiles(128, pick_tn) > target && - tiles(64, 128) <= target) - ? tiles(64, 128) - : tiles(128, pick_tn); - // c fits in one wave at > 50%, and either the current choice - // needs more than one wave or c gives more CTAs. - auto fills_better = [&](int64_t c) { - return c <= target && 2 * c > target && - (incumbent_ctas > target || c > incumbent_ctas); - }; - // The 256x64 pair tile above was skipped in favour of 64x96; - // take 64x96 even though it exceeds one wave. - const bool pair_deferred_to_96 = - (m % 256 == 0) && (n % 64 == 0) && (n % 128 != 0) && - (k % 64 == 0) && - (static_cast(m / 256) * CeilDiv(n, 64) * 2 > target); - if (!tile96_disabled && (m % 64 == 0) && (n % 32 == 0) && - (fills_better(ctas96) || pair_deferred_to_96) && - (k / kBF16BlockK) >= kMidMDeepPrologueMinKTiles) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x96x64_1CTA_P11>(); - } - if (!tile224_disabled && (m % 64 == 0) && (n % 32 == 0) && - fills_better(ctas224)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x224x64_1CTA_P6>(); - } - - if (!wave64_disabled && (m % 64 == 0) && (n % 128 == 0) && - tiles(128, pick_tn) > target && - (wave64_anycta || tiles(64, 128) <= target)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA>(); - } - - // ---- 128x64 pair-UMMA, 18 stages -------------------------------- - // Used when the grid is one wave with enough K-tiles, or when the - // 128xN choice is 128x128 (only 4 stages). Its CTA count stays in - // the correct band. HALOPS_DISABLE_PAIR_DEEP=1 disables it. - static const bool pairdeep_disabled = - EnvIs("HALOPS_DISABLE_PAIR_DEEP", "1"); - if (!pairdeep_disabled && (m % 128 == 0) && (n % 128 == 0) && - (k % 64 == 0)) { - const int pd_target = ResolveSmCount(sm_count); - const int64_t pair_ctas = PairDeepCtaCount(m, n); - const int64_t pair_k_tiles = k / kBF16BlockK; - const bool one_wave = - pair_ctas <= pd_target && 2 * pair_ctas > pd_target; - const bool deep_enough = pair_k_tiles >= kMidMDeepPrologueMinKTiles; - const bool shallow_incumbent = (pick == 1); - if ((one_wave && deep_enough) || shallow_incumbent) { - // With <= 64 K-tiles, 64x64x64_1WG_P14 is faster. - // HALOPS_PAIRDEEP_SHORTK=0 disables it. - static const bool pairdeep_shortk = - EnvNot0("HALOPS_PAIRDEEP_SHORTK"); - if (pairdeep_shortk && one_wave && deep_enough && - pair_k_tiles <= 64 && (m % 64 == 0) && (n % 64 == 0)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18>(); - } - } - if (pick == 3) { - // HALOPS_TILE_K32=1 swaps in 128x32x32 (16 stages). - static const bool k32_enabled = EnvIs("HALOPS_TILE_K32", "1"); - if (k32_enabled && (k % 32 == 0)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x32x32_1CTA>(); - } - // HALOPS_THINM_STAGES=4|6 forces a shallower prologue. - static const int thinm_stages = EnvIntOr("HALOPS_THINM_STAGES", 0); - if (thinm_stages == 4) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x32x64_P4_1CTA>(); - } - if (thinm_stages == 6) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x32x64_P6_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x32x64_1CTA>(); - } - if (pick == 2) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA>(); - } - if (pick == 1) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x128x64_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x256x64_1CTA>(); - } - - if (ThinMNoSwapOk(m, n, k, sm_count)) { - // ---- m < 128 without SwapAB ------------------------------------ - // At m=64 SwapAB yields too few CTAs; KBlockM=64 tiles give - // ceil(n/32). Use 64x32 if it fits one wave, else 64x64. - const int target = ResolveSmCount(sm_count); - const int64_t mt = CeilDiv(m, 64); - const int64_t nt32 = CeilDiv(n, 32); - if (nt32 * mt <= target && (n % 32 == 0)) { - if (DeepProloguePays(k)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_1CTA>(); - } - // HALOPS_M64_1WG_DEEP=0 restores the 10-stage config. - static const bool thin_1wg_deep = EnvNot0("HALOPS_M64_1WG_DEEP"); - if (thin_1wg_deep && DeepProloguePays(k)) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA>(); - } - - // Small-N SwapAB: weight (N×K) → UMMA A (M-dim=128), activation - // (M×K) → UMMA B (N-dim=64). - if (n % 128 != 0 || m % 64 != 0 || k % 64 != 0) { - return -1; - } - // Use KBlockK=128 for k >= 8192. HALOPS_DISABLE_SWAPAB_K128=1 - // disables it. - static const bool swapab_k128_disabled = - EnvIs("HALOPS_DISABLE_SWAPAB_K128", "1"); - if (!swapab_k128_disabled && (k % 128 == 0) && k >= 8192) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA>(); - } - // Use the 256-wide pair tile when the 128-wide grid exceeds 2 - // waves. HALOPS_DISABLE_SWAPAB_N256=1 disables it. - static const bool swapab_n256_disabled = - EnvIs("HALOPS_DISABLE_SWAPAB_N256", "1"); - const int swapab_target = ResolveSmCount(sm_count); - const int64_t swapab_tiles128 = CeilDiv(n, 128) * CeilDiv(m, 64); - if (!swapab_n256_disabled && (n % 256 == 0) && - swapab_tiles128 > 2 * swapab_target) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias256x64x64_SwapAB_2CTA>(); - } - // Use KBlockN=32 if that still fits one wave. - // HALOPS_DISABLE_SWAPAB_N32=1 disables it. - static const bool swapab_n32_disabled = - EnvIs("HALOPS_DISABLE_SWAPAB_N32", "1"); - const int64_t swapab_tiles64 = CeilDiv(n, 128) * CeilDiv(m, 32); - if (!swapab_n32_disabled && swapab_tiles64 <= swapab_target) { - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x32x64_SwapAB_1CTA>(); - } - return bf16_dispatch::BF16TileIndex< - GemmKernelConfigBF16NaiveNoBias128x64x64_SwapAB_1CTA>(); -} - -} // namespace dense - -// --------------------------------------------------------------------------- -// Grouped/batch catalogs and selectors (moved verbatim from their .cu -// host functions). -// --------------------------------------------------------------------------- - -using BF16ContiguousTiles = cute::tuple< - GemmKernelConfigBF16ContiguousNoBias256x256x64_2CTA, // 0 - GemmKernelConfigBF16ContiguousNoBias256x128x64_2CTA, // 1 - GemmKernelConfigBF16ContiguousNoBias128x256x64_1CTA, // 2 - GemmKernelConfigBF16ContiguousNoBias128x128x64_1CTA, // 3 - GemmKernelConfigBF16ContiguousNoBias128x64x64_1CTA, // 4 - GemmKernelConfigBF16ContiguousNoBias128x64x64_SwapAB_1CTA>; // 5 -constexpr int kBF16ContiguousCount = - static_cast(cute::tuple_size_v); - -using BF16MaskedTiles = - cute::tuple; // 5 -constexpr int kBF16MaskedCount = - static_cast(cute::tuple_size_v); - -using BF16BatchTiles = - cute::tuple; // 2 -constexpr int kBF16BatchCount = - static_cast(cute::tuple_size_v); - -// group_contiguous: m is the total token count. -inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { - if (m >= 4096) { - return 0; - } - if (m >= 128) { - // Step finer on N only while the coarser tile underfills the SM - // grid. M stays 128 (BF16 dummy-SF 1-CTA MMA requires M==128). - const int target_sm = ResolveSmCount(sm_count); - auto tiles = [&](int tm, int tn) { - return ((m + tm - 1) / tm) * ((n + tn - 1) / tn); - }; - // Step 0: 2-CTA pair-UMMA 256x256 (weight TMA-multicast across the - // pair, much higher per-SM MMA throughput than 1-CTA 128x256). - // Each cluster spans 2 SMs: require clusters*2 >= target_sm. - // Needs m%256, n%256, k%64. - const int clusters_2cta = ((m + 255) / 256) * ((n + 255) / 256); - if (m % 256 == 0 && n % 256 == 0 && k % 64 == 0 && - clusters_2cta * 2 >= target_sm) { - // 256x128 frees a deeper (8- vs 6-stage) pipeline; pays only - // when 256x256 is lightly oversubscribed (<= ~2 waves). - const bool square_like = - (n % 128 == 0) && (clusters_2cta <= 2 * target_sm); - return square_like ? 1 : 0; - } - // N-tile ladder: 128x128 when 128x256 underfills; 128x64 only on a - // <=1-wave fit, since halving N doubles M*K panel reloads (costly - // on DRAM-bound mid-M). - int pick = 2; - if (tiles(128, 256) < target_sm && (n % 128 == 0)) { - pick = 3; - if (tiles(128, 64) <= target_sm && (n % 64 == 0)) { - pick = 4; - } - } - return pick; - } - return 5; // SwapAB -} - -// group_masked: tiles scale with num_experts; mm is max_m_per_expert. -inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, - int sm_count) { - if (mm >= 4096) { - return 4; - } - if (mm >= 128) { - // Masked pads every expert to max_m_per_expert, so tiles = - // num_experts * ceil(max_m/tm) * ceil(n/tn). M stays 128. - const int target_sm = ResolveSmCount(sm_count); - auto tiles = [&](int tm, int tn) { - return num_experts * ((mm + tm - 1) / tm) * ((n + tn - 1) / tn); - }; - const int clusters_2cta = - num_experts * ((mm + 255) / 256) * ((n + 255) / 256); - if (mm % 256 == 0 && n % 256 == 0 && k % 64 == 0 && - clusters_2cta * 2 >= target_sm) { - const bool square_like = - (n % 128 == 0) && (clusters_2cta <= 2 * target_sm); - return square_like ? 5 : 4; - } - // N-tile ladder: keep 128x256 (best B-reuse) unless it underfills - // the grid; a blanket 128x128 preference regresses oversubscribed - // mid-M. - int pick = 0; - if (tiles(128, 256) < target_sm && (n % 128 == 0)) { - pick = 2; - // 128x64 only on a <=1-wave fit: halving N doubles M*K panel - // reloads (costly on DRAM-bound mid-M). - if (tiles(128, 64) <= target_sm && (n % 64 == 0)) { - pick = 3; - } - } - return pick; - } - return 1; // SwapAB -} - -// batch: pure alignment ladder (no runtime SM reasoning). -inline int SelectBF16BatchCfg(int m_per_item, int n, int k) { - if (m_per_item % 256 == 0 && n % 256 == 0) { - return 0; - } - if (m_per_item % 128 == 0 && n % 256 == 0) { - return 1; - } - if (m_per_item % 64 == 0 && n % 128 == 0) { - return 2; - } - return -1; -} - -template -constexpr std::array MakeBF16DescTable( - std::index_sequence) { - return {{MakeBF16Desc>()...}}; -} - -constexpr auto kBF16ContiguousCfgs = MakeBF16DescTable( - std::make_index_sequence{}); -constexpr auto kBF16MaskedCfgs = MakeBF16DescTable( - std::make_index_sequence{}); -constexpr auto kBF16BatchCfgs = MakeBF16DescTable( - std::make_index_sequence{}); - -// Divisibility validation for a selected grouped/batch cfg, with the same -// per-rung contract the .cu ladders enforced (N relaxes to %32 for -// non-power-of-2 widths, %64 for predicated tails). -inline void CheckBF16CfgShape(const char* what, const BF16CfgDesc& d, int m, - int n, int k) { - const int n_mod = d.ntail ? 64 : (((d.bn & (d.bn - 1)) != 0) ? 32 : d.bn); - // SwapAB: KBlockM tiles the weight (output N), KBlockN the activation - // (output M). - const int m_div = d.swap ? d.bn : d.bm; - const int n_div = d.swap ? d.bm : n_mod; - TORCH_CHECK(m % m_div == 0, what, " requires M to be divisible by ", m_div, - ", got ", m); - TORCH_CHECK(n % n_div == 0, what, " requires N to be divisible by ", n_div, - ", got ", n); - TORCH_CHECK(k % d.bk == 0, what, " requires K to be divisible by ", d.bk, - ", got ", k); -} - -// Generic id->tile dispatcher for the small catalogs above. -template -void DispatchBF16SmallCfg(int cfg, const char* what, LaunchTile&& launch) { - const bool found = [&](std::integer_sequence) { - return ((cfg == Is ? (launch.template - operator()>(), - true) - : false) || - ...); - }(std::make_integer_sequence{}); - TORCH_CHECK(found, "unknown ", what, " cfg id ", cfg); -} - -// Launch dispatch: maps a catalog id to the tile instantiation. One branch -// per catalog entry, generated from the tuple (gemm_tile.cuh's DispatchCfgAt -// lives in an anonymous namespace, so this is a local twin). -template -void DispatchBF16Cfg(int cfg, LaunchTile&& launch) { - const bool found = [&](std::integer_sequence) { - return ((cfg == Is - ? (launch.template - operator()>(), - true) - : false) || - ...); - }(std::make_integer_sequence{}); - TORCH_CHECK(found, "unknown bf16 cfg id ", cfg); -} - -} // namespace bf16_dispatch -} // namespace halops diff --git a/csrc/kernel/gemm/dense_gemm.cu b/csrc/kernel/gemm/dense_gemm.cu index c6651b4..cce33ce 100644 --- a/csrc/kernel/gemm/dense_gemm.cu +++ b/csrc/kernel/gemm/dense_gemm.cu @@ -15,7 +15,6 @@ #include #include -#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -23,8 +22,8 @@ namespace halops { void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, const std::optional& sfa, - const std::optional& sfb, - torch::Tensor& output, const std::optional& bias, + const std::optional& sfb, torch::Tensor& output, + const std::optional& bias, const std::optional& alpha, const int sm_count_arg, const std::string& mode, const bool use_pdl, const EpilogueOp epilogue, @@ -74,15 +73,8 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, : 0.0f}; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored. - using TypeA = cutlass::bfloat16_t; - using TypeB = cutlass::bfloat16_t; - using TypeC = cutlass::bfloat16_t; - using TypeD = cutlass::bfloat16_t; - // Placeholder, never dereferenced. - using TypeSF = cutlass::float_ue8m0_t; - using TypeAccumulate = float; - + // Native BF16: sfa/sfb/bias/alpha are ignored; the tile ladder, + // validation and launch live in gemm_dispatch.cuh (bf16::LaunchDense). TORCH_CHECK(input.dtype() == torch::kBFloat16, "bf16 dense GEMM: input must be bfloat16"); TORCH_CHECK(weight.dtype() == torch::kBFloat16, @@ -104,179 +96,17 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_c = nullptr; params.ptr_alpha = nullptr; - // Debug only: HALOPS_FORCE_CFG=256x128x64_2CTA (any name in kKnown, - // i.e. GemmKernelConfigBF16NaiveNoBias) skips the dispatch below - // and runs that config on every shape it supports; other shapes are - // dispatched normally. - static const std::string forced_cfg = [] { - const char* e = std::getenv("HALOPS_FORCE_CFG"); - std::string name(e == nullptr ? "" : e); - static const char* kKnown[] = { - "", - "256x256x64_2CTA", - "256x256x64_2CTA_P7", - "256x128x64_2CTA", - "256x128x64_2CTA_Ntail", - "256x128x64_2CTA_P9", - "256x128x64_2CTA_P9_Ntail", - "256x192x64_2CTA", - "256x64x64_2CTA", - "128x256x64_1CTA", - "128x128x64_1CTA", - "128x64x64_1CTA", - "128x32x64_1CTA", - "128x64x64_2CTA_P18", - "64x224x64_1CTA_P6", - "64x128x64_1CTA", - "64x96x64_1CTA_P11", - "64x64x64_1CTA", - "64x64x64_1WG_1CTA", - "64x64x64_P12_1CTA", - "64x64x64_P14_1CTA", - "64x32x64_1WG_P14_1CTA", - "64x32x64_1WG_P18_1CTA", - "64x64x64_1WG_P14_1CTA", - }; - bool known = false; - for (const char* k : kKnown) { - known = known || name == k; - } - TORCH_CHECK(known, "HALOPS_FORCE_CFG=", name, - " is not a config name this hatch knows; see the " - "kKnown list in dense_gemm.cu."); - return name; - }(); - if (!forced_cfg.empty()) { - // Required n alignment: 32 for non-power-of-2 KBlockN, 64 for - // _Ntail configs, KBlockN otherwise. -#define HALOPS_FORCE_TRY(NAME, CFG, EXTRA) \ - if (forced_cfg == NAME) { \ - using KernelConfig = CFG; \ - constexpr int kNMod = \ - KernelConfig::KForceEpiNPredicate \ - ? 64 \ - : ((KernelConfig::KBlockN & (KernelConfig::KBlockN - 1)) != 0 \ - ? 32 \ - : KernelConfig::KBlockN); \ - constexpr int kNModCluster = kNMod * KernelConfig::KClusterN; \ - if (m % KernelConfig::KBlockM == 0 && n % kNModCluster == 0 && \ - k % KernelConfig::KBlockK == 0 && (EXTRA)) { \ - gemm_impl(params, sm, stream); \ - return; \ - } \ - } - HALOPS_FORCE_TRY("256x256x64_2CTA", - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA, - true) - HALOPS_FORCE_TRY("256x256x64_2CTA_P7", - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA_P7, - true) - HALOPS_FORCE_TRY("256x128x64_2CTA", - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA, - true) - HALOPS_FORCE_TRY( - "256x128x64_2CTA_Ntail", - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail, true) - HALOPS_FORCE_TRY("256x128x64_2CTA_P9", - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9, - true) - HALOPS_FORCE_TRY( - "256x128x64_2CTA_P9_Ntail", - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail, true) - HALOPS_FORCE_TRY("256x192x64_2CTA", - GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA, - true) - HALOPS_FORCE_TRY("256x64x64_2CTA", - GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA, - true) - HALOPS_FORCE_TRY("128x256x64_1CTA", - GemmKernelConfigBF16NaiveNoBias128x256x64_1CTA, - true) - HALOPS_FORCE_TRY("128x128x64_1CTA", - GemmKernelConfigBF16NaiveNoBias128x128x64_1CTA, - true) - HALOPS_FORCE_TRY("128x64x64_1CTA", - GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA, - true) - HALOPS_FORCE_TRY("128x32x64_1CTA", - GemmKernelConfigBF16NaiveNoBias128x32x64_1CTA, - true) - // Only within the correct CTA band. - HALOPS_FORCE_TRY("128x64x64_2CTA_P18", - GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18, - bf16_dispatch::PairDeepCtaCount(m, n) >= - bf16_dispatch::kPairDeepMinCtas && - bf16_dispatch::PairDeepCtaCount(m, n) <= - bf16_dispatch::kPairDeepMaxCtas) - HALOPS_FORCE_TRY("64x224x64_1CTA_P6", - GemmKernelConfigBF16NaiveNoBias64x224x64_1CTA_P6, - true) - HALOPS_FORCE_TRY("64x128x64_1CTA", - GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA, - true) - HALOPS_FORCE_TRY("64x96x64_1CTA_P11", - GemmKernelConfigBF16NaiveNoBias64x96x64_1CTA_P11, - true) - HALOPS_FORCE_TRY("64x64x64_1CTA", - GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA, true) - HALOPS_FORCE_TRY("64x64x64_1WG_1CTA", - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA, - true) - HALOPS_FORCE_TRY("64x64x64_P12_1CTA", - GemmKernelConfigBF16NaiveNoBias64x64x64_P12_1CTA, - true) - HALOPS_FORCE_TRY("64x64x64_P14_1CTA", - GemmKernelConfigBF16NaiveNoBias64x64x64_P14_1CTA, - true) - HALOPS_FORCE_TRY( - "64x32x64_1WG_P14_1CTA", - GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P14_1CTA, true) - HALOPS_FORCE_TRY( - "64x32x64_1WG_P18_1CTA", - GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA, true) - HALOPS_FORCE_TRY( - "64x64x64_1WG_P14_1CTA", - GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA, true) -#undef HALOPS_FORCE_TRY - } - - // Entry guards per tier (same messages the per-rung checks used). + // Entry guards per tier (friendlier messages than the per-tile checks). if (m >= 128 && m < 4096) { CheckDivisible(m, 128, "BF16 GEMM mid M M"); CheckDivisible(n, 32, "BF16 GEMM mid M N"); CheckDivisible(k, 64, "BF16 GEMM mid M K"); - } else if (m < 128 && !bf16_dispatch::ThinMNoSwapOk(m, n, k, sm)) { + } else if (m < 128 && !bf16::SkipSwapForThinM(m, n, k, sm)) { CheckDivisible(n, 128, "BF16 GEMM SwapAB N"); CheckDivisible(m, 64, "BF16 GEMM SwapAB M"); CheckDivisible(k, 64, "BF16 GEMM SwapAB K"); } - const int cfg = bf16_dispatch::dense::SelectBF16Cfg(m, n, k, sm); - TORCH_CHECK(cfg >= 0, "No BF16 dense GEMM tile supports M=", m, - ", N=", n, ", K=", k); - const auto& desc = bf16_dispatch::kBF16Cfgs[cfg]; - // Same divisibility contract the per-rung checks enforced: the - // output M/N tile multiples (N may relax to %32 for non-power-of-2 - // widths or %64 for predicated-tail tiles), K a KBlockK multiple. - // SwapAB swaps the roles: KBlockM tiles the weight (output N) and - // KBlockN the activation (output M). - const int n_mod = - desc.ntail ? 64 : (((desc.bn & (desc.bn - 1)) != 0) ? 32 : desc.bn); - const int m_div = desc.swap ? desc.bn : desc.bm; - const int n_div = desc.swap ? desc.bm : n_mod; - TORCH_CHECK(m % m_div == 0, - "BF16 dense GEMM requires M to be divisible by ", m_div, - ", got ", m); - TORCH_CHECK(n % n_div == 0, - "BF16 dense GEMM requires N to be divisible by ", n_div, - ", got ", n); - TORCH_CHECK(k % desc.bk == 0, - "BF16 dense GEMM requires K to be divisible by ", desc.bk, - ", got ", k); - bf16_dispatch::DispatchBF16Cfg(cfg, [&]() { - gemm_impl(params, sm, stream); - }); + bf16::LaunchDense(params, sm, stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 dense GEMM requires sfa/sfb scale factors " diff --git a/csrc/kernel/gemm/gemm_dispatch.cuh b/csrc/kernel/gemm/gemm_dispatch.cuh index f3b4cb9..ece205d 100644 --- a/csrc/kernel/gemm/gemm_dispatch.cuh +++ b/csrc/kernel/gemm/gemm_dispatch.cuh @@ -26,6 +26,7 @@ #include "kernel/gemm/gemm_kernel.cuh" #include "kernel/gemm/gemm_tile.cuh" #include "kernel/gemm/gemm_tuned_dense_fp8.cuh" +#include "kernel/gemm/gemm_utils.h" namespace halops { @@ -356,10 +357,14 @@ inline int PickTile(const TileSpec* tiles, int count, MmaKind kind, // Dispatch using TileLauncher = void (*)(GemmParams&, const GemmShape&, cudaStream_t); -template +// Candidates is any type exposing `static constexpr tiles`: +// CandidateTiles for the cost-model tables, or the per-mode BF16 tables +// below. +template void LaunchTile(GemmParams& params, const GemmShape& shape, cudaStream_t stream) { - constexpr TileSpec S = CandidateTiles::tiles[I]; + constexpr TileSpec S = Candidates::tiles[I]; if constexpr (TileAllowedFor(S, Mode) && (!IsQuantOp(Op) || (Kind == MmaKind::MXFP8 && S.quantizes()))) { @@ -376,15 +381,18 @@ void LaunchTile(GemmParams& params, const GemmShape& shape, } } -template +template constexpr std::array MakeTileLaunchers( std::index_sequence) { - return {&LaunchTile...}; + return {&LaunchTile...}; } -template -inline constexpr auto kTileLaunchers = MakeTileLaunchers( - std::make_index_sequence::tiles.size()>{}); +template > +inline constexpr auto kTileLaunchers = + MakeTileLaunchers( + std::make_index_sequence{}); inline bool GemmTraceEnabled() { static const bool on = std::getenv("IR_GEMM_TRACE") != nullptr; @@ -417,4 +425,631 @@ void LaunchCfg(GemmParams& params, GemmShape shape, cudaStream_t stream) { kTileLaunchers[pick](params, shape, stream); } +// =========================================================================== +// BF16 dispatch. Rule-based rather than cost-model based: the ladder below +// encodes measured launch-shape bands (pair-UMMA gates, wave-fill judgements, +// K-tile depth gates). A selector returns an index into the per-mode tile +// tables in gemm_tile.cuh, or -1 when no tile supports the shape; the launch +// helpers validate the selected tile and run it. +// =========================================================================== +namespace bf16 { + +// KBlockK of every BF16 tile. +inline constexpr int kBlockK = 64; + +// Deep-pipeline tiles (14/18 stages) only pay off from this many K-tiles. +inline constexpr int kDeepPipelineMinKTiles = 32; + +// The 64x96 / 128x64-pair deep tiles need at least this many K-tiles. +inline constexpr int kMidMDeepMinKTiles = 54; + +// 256x128 re-reads A twice as often as 256x256; beyond this many K-tiles the +// re-read outweighs any wave-packing gain. +inline constexpr int kNarrowPairMaxKTiles = 64; + +// A 64-row tile has no multicast, so every extra N-tile re-reads A; cap the +// re-read volume (k_tiles * n_tiles) before stepping down to one. +inline constexpr int kRereadsCap = 2048; + +// True if the deep (14/18-stage) pipeline variant pays off at this K. +inline bool UseDeepPipeline(int k) { + return k / kBlockK >= kDeepPipelineMinKTiles; +} + +// CTAs the 128x64 pair-tile family yields (2 CTAs per cluster tile). +inline int64_t Count128x64PairCtas(int m, int n) { + return 2 * int64_t(CeilDiv(m, 128)) * CeilDiv(n, 64); +} + +// For m < 128: a plain (non-SwapAB) 64-row tile beats SwapAB when even +// SwapAB's smallest tile leaves SMs idle. +inline bool SkipSwapForThinM(int m, int n, int k, int sm_count) { + if (m % 64 != 0 || k % 64 != 0) { + return false; + } + const int target = ResolveSmCount(sm_count); + const int mt = CeilDiv(m, 64); + const bool narrow_ok = (n % 32 == 0) && (CeilDiv(n, 32) * mt <= target); + const bool square_ok = (n % 64 == 0); + if (!narrow_ok && !square_ok) { + return false; + } + return CeilDiv(n, 128) * CeilDiv(m, 32) < target; +} + +// True if the fine grid keeps a larger fraction of SMs busy (ctas / waves). +inline bool FillsLastWaveBetter(int64_t coarse_ctas, int64_t fine_ctas, + int64_t target) { + const int64_t coarse_waves = (coarse_ctas + target - 1) / target; + const int64_t fine_waves = (fine_ctas + target - 1) / target; + return fine_ctas * coarse_waves > coarse_ctas * fine_waves; +} + +// 256x128 instead of 256x256 when K is short, the grid is not too deep, and +// 256x128 keeps more SMs busy. +inline bool UseNarrowPairTile(int n, int k, int64_t coarse_ctas, + int64_t fine_ctas, int64_t target) { + return (n % 128 == 0) && (k / kBlockK <= kNarrowPairMaxKTiles) && + (coarse_ctas <= 4 * target) && + FillsLastWaveBetter(coarse_ctas, fine_ctas, target); +} + +// ---- Small-N (N <= 128) tiles ---------------------------------------------- + +inline constexpr int kSmallNMaxN = 128; +inline constexpr int kSmallNAlignN = 64; + +enum class SmallNTile { kNone, kPairM256N128, kM64N128, kPairM256N64, kM64N64 }; + +struct SmallNRung { + SmallNTile tile; + int block_m; + int block_n; + int ctas_per_cluster; +}; + +inline bool FillsOneWave(int64_t ctas, int64_t target) { + return ctas <= target && 2 * ctas > target; +} + +// N fits one tile, so all CTAs come from splitting M: pick the largest tile +// whose CTA count lands in (0.5, 1.0] of one wave. +inline SmallNTile PickSmallNTile(int m, int n, int64_t target) { + if (n > kSmallNMaxN || n % kSmallNAlignN != 0) { + return SmallNTile::kNone; + } + static constexpr SmallNRung kRungs[] = { + {SmallNTile::kPairM256N128, 256, 128, 2}, + {SmallNTile::kM64N128, 64, 128, 1}, + {SmallNTile::kPairM256N64, 256, 64, 2}, + {SmallNTile::kM64N64, 64, 64, 1}, + }; + for (const SmallNRung& r : kRungs) { + const int64_t ctas = int64_t(r.ctas_per_cluster) * + CeilDiv(m, r.block_m) * CeilDiv(n, r.block_n); + if (FillsOneWave(ctas, target)) { + return r.tile; + } + } + return SmallNTile::kNone; +} + +// ---- Dense ----------------------------------------------------------------- +// Ids into kBF16DenseTiles (gemm_tile.cuh); the enum order mirrors the table. +enum DenseTile : int { + kPair256x256, // 256x256 pair, 6 stages + kPair256x256P7, + kPair256x128, // 8 stages + kPair256x128Ntail, + kPair256x128P9, + kPair256x128P9Ntail, + kPair256x192, + kPair256x64, // 10 stages + kM128x256, + kM128x128, + kM128x64, // 8 stages + kM128x32, // 10 stages + kPair128x64P18, // 18 stages, 1 epilogue warp group + kM64x128, + kM64x96P11, // 11 stages, 1 epilogue warp group + kM64x224, // 1 epilogue warp group + kM64x64, // 2 epilogue warp groups, 10 stages + kM64x64_1wg, + kM64x64_1wgP14, + kM64x32_1wg, + kM64x32_1wgP18, + kSwap128x64, + kSwap128x32, + kSwap256x64Pair, + kSwap128x64K128, // SwapAB, KBlockK=128 (k >= 8192) +}; +static_assert(kSwap128x64K128 + 1 == static_cast(kBF16DenseTiles.size()), + "BF16 dense tile table and DenseTile enum drifted apart"); + +// m >= 4096: pair tiles, with a small-N ladder for narrow N. +inline int SelectLargeMTile(int m, int n, int k, int target) { + switch (PickSmallNTile(m, n, target)) { + case SmallNTile::kM64N128: + return kM64x128; + case SmallNTile::kM64N64: + return UseDeepPipeline(k) ? kM64x64_1wgP14 : kM64x64; + case SmallNTile::kPairM256N64: + return kPair256x64; + case SmallNTile::kPairM256N128: + case SmallNTile::kNone: + break; + } + const int64_t tiles_256 = int64_t(CeilDiv(m, 256)) * CeilDiv(n, 256); + // 256x128 (deeper pipeline) when it keeps more SMs busy on a short K. + if (UseNarrowPairTile(n, k, 2 * tiles_256, + 2 * int64_t(CeilDiv(m, 256)) * CeilDiv(n, 128), + target)) { + return kPair256x128P9; + } + if (n % 256 == 0) { + return kPair256x256P7; + } + if (n % 128 == 0) { + return kPair256x128; + } + // n % 128 != 0 (e.g. 1600): predicated-tail 128-wide tile, else 256x64. + if (n % 64 == 0) { + return kPair256x128Ntail; + } + return kPair256x64; +} + +// Halve the 128-row tile's N (256 -> 128 -> 64 -> 32) while the current width +// leaves SMs idle. Returns the chosen N width. +inline int Pick128xNWidth(int m, int n, int target) { + auto tiles = [&](int tm, int tn) { + return CeilDiv(m, tm) * CeilDiv(n, tn); + }; + int pick = (n % 256 == 0) ? 0 : (n % 128 == 0) ? 1 : (n % 64 == 0) ? 2 : 3; + // Keep 128x256 when 128x128 would spill into a second wave. + const bool overshoots_128 = + m > 128 && tiles(128, 128) > target && 2 * tiles(128, 256) > target; + if (pick == 0 && tiles(128, 256) < target && (n % 128 == 0) && + !overshoots_128) { + pick = 1; + } + if (pick == 1 && tiles(128, 128) < target && (n % 64 == 0)) { + pick = 2; + } + if (pick == 2 && tiles(128, 64) < target && (n % 32 == 0)) { + pick = 3; + } + return pick == 0 ? 256 : (pick == 1 ? 128 : (pick == 2 ? 64 : 32)); +} + +// 256xN pair-UMMA ladder for m % 256 == 0; returns -1 when its gates reject +// the shape and the 128xN ladder should decide instead. +inline int SelectPair256xNTile(int m, int n, int k, int target) { + if (n % 64 != 0) { + return -1; + } + auto pair_ctas = [&](int tn) { + return int64_t(m / 256) * CeilDiv(n, tn) * 2; + }; + // Halve N only while the grid is under one wave, and never from >= half + // a wave into more than one wave. + auto step_ok = [&](int coarse, int fine) { + return pair_ctas(coarse) < target && + !(pair_ctas(fine) > target && 2 * pair_ctas(coarse) > target); + }; + int pair_tn = (n % 256 == 0) ? 256 : ((n % 128 == 0) ? 128 : 64); + // n % 128 != 0 (e.g. 1600): the 128-wide predicated-tail tile instead of + // 64 if it fills at least half a wave. + bool pair_n_tail = false; + if (pair_tn == 64 && (n % 128 != 0) && 2 * pair_ctas(128) >= target) { + pair_tn = 128; + pair_n_tail = true; + } + // Also 128 when the narrow-pair rule says so (multi-wave). + if (pair_tn == 256 && (n % 128 == 0) && + (step_ok(256, 128) || + UseNarrowPairTile(n, k, pair_ctas(256), pair_ctas(128), target))) { + pair_tn = 128; + } + // 192 if it fits one wave and keeps more SMs busy than both 256 and 128. + if (pair_tn != 64 && (n % 32 == 0) && pair_ctas(192) <= target && + FillsLastWaveBetter(pair_ctas(256), pair_ctas(192), target) && + FillsLastWaveBetter(pair_ctas(128), pair_ctas(192), target)) { + pair_tn = 192; + pair_n_tail = false; + } + if (!pair_n_tail && pair_tn == 128 && (n % 64 == 0) && step_ok(128, 64)) { + pair_tn = 64; + } + const int64_t cta_count = pair_ctas(pair_tn); + const int k_tiles = k / kBlockK; + // Prologue amortization: enough K-tiles to fill three pipelines, or a + // full wave of tiles. + const int stages = + pair_tn == 256 ? 6 : (pair_tn == 192 ? 8 : (pair_tn == 128 ? 8 : 10)); + const bool amortizes = k_tiles >= 3 * stages || cta_count >= target; + // The 64-wide arm needs at least 0.8 of a wave. + const bool narrow_arm_fills = pair_tn != 64 || 5 * cta_count >= 4 * target; + // If n % 128 != 0 forced 256x64 and it spills past one wave, defer to the + // 64x96 / 64x224 tiles below. + const int ctas96 = CeilDiv(m, 64) * CeilDiv(n, 96); + const int ctas224 = CeilDiv(m, 64) * CeilDiv(n, 224); + const bool narrow_arm_overshoots = + pair_tn == 64 && cta_count > target && (m % 64 == 0) && (n % 32 == 0) && + (!(k_tiles >= kMidMDeepMinKTiles) || + FillsLastWaveBetter(ctas224, ctas96, target)); + if (!amortizes || !narrow_arm_fills || narrow_arm_overshoots) { + return -1; + } + switch (pair_tn) { + case 256: + return kPair256x256; + case 192: + return kPair256x192; + case 128: + return pair_n_tail ? kPair256x128P9Ntail : kPair256x128P9; + default: + // With <= 32 K-tiles the 1-CTA 128x64 tile (same CTA count) is + // faster than the 256x64 pair. + return k_tiles <= 32 ? kM128x64 : kPair256x64; + } +} + +// 128 <= m < 4096. +inline int SelectMidMTile(int m, int n, int k, int target) { + if (m % 128 != 0 || n % 32 != 0 || k % 64 != 0) { + return -1; + } + + // ---- 64-row tiles (64x64 / 64x32) ---------------------------------- + // Smaller tiles add CTAs but, with no multicast, every extra N-tile + // re-reads A; use them only on a one-wave grid with bounded re-reads. + if (m % 64 == 0 && n % 64 == 0) { + const int tiles64 = CeilDiv(m, 64) * CeilDiv(n, 64); + const int64_t rereads = int64_t(k / kBlockK) * CeilDiv(n, 64); + if (tiles64 <= target && rereads <= kRereadsCap) { + // 1 epilogue warp group: required for 64x32, and it skips the + // inter-warp-group barrier on 64x64. + if (2 * tiles64 <= target && n % 32 == 0) { + return UseDeepPipeline(k) ? kM64x32_1wgP18 : kM64x32_1wg; + } + return UseDeepPipeline(k) ? kM64x64_1wgP14 : kM64x64_1wg; + } + } + + // ---- 256xN pair-UMMA tiles (m % 256 == 0) -------------------------- + if (m % 256 == 0) { + const int pair = SelectPair256xNTile(m, n, k, target); + if (pair >= 0) { + return pair; + } + } + + // ---- 128xN width ---------------------------------------------------- + const int pick_tn = Pick128xNWidth(m, n, target); + auto tiles = [&](int tm, int tn) { + return CeilDiv(m, tm) * CeilDiv(n, tn); + }; + + // ---- 64x96 / 64x224 fill tiles -------------------------------------- + // Power-of-2 N widths can miss one wave entirely (n=7168: 112 or 224 CTAs + // on 152 SMs); 96/224 land in between. + const int ctas96 = CeilDiv(m, 64) * CeilDiv(n, 96); + const int ctas224 = CeilDiv(m, 64) * CeilDiv(n, 224); + // The incumbent is the 128xN choice, adjusted for the 64x128 wave fix + // below when that applies. + const int incumbent_ctas = (n % 128 == 0 && tiles(128, pick_tn) > target && + tiles(64, 128) <= target) + ? tiles(64, 128) + : tiles(128, pick_tn); + auto fills_better = [&](int64_t c) { + return c <= target && 2 * c > target && + (incumbent_ctas > target || c > incumbent_ctas); + }; + // The 256x64 pair arm deferred here in favour of 64x96; take it even + // though it exceeds one wave. + const bool pair_deferred_to_96 = + (m % 256 == 0) && (n % 64 == 0) && (n % 128 != 0) && + (int64_t(m / 256) * CeilDiv(n, 64) * 2 > target); + if ((m % 64 == 0) && (n % 32 == 0) && + (fills_better(ctas96) || pair_deferred_to_96) && + (k / kBlockK) >= kMidMDeepMinKTiles) { + return kM64x96P11; + } + if ((m % 64 == 0) && (n % 32 == 0) && fills_better(ctas224)) { + return kM64x224; + } + + // ---- 64x128 when the 128xN tile spills past one wave ----------------- + if ((m % 64 == 0) && (n % 128 == 0) && tiles(128, pick_tn) > target && + tiles(64, 128) <= target) { + return kM64x128; + } + + // ---- 128x64 pair, 18 stages ------------------------------------------ + // One wave with enough K-tiles, or the 128x128 incumbent (only 4 stages). + if ((m % 128 == 0) && (n % 128 == 0)) { + const int64_t pair_ctas = Count128x64PairCtas(m, n); + const int k_tiles = k / kBlockK; + const bool one_wave = pair_ctas <= target && 2 * pair_ctas > target; + const bool deep_enough = k_tiles >= kMidMDeepMinKTiles; + const bool shallow_incumbent = (pick_tn == 128); + if ((one_wave && deep_enough) || shallow_incumbent) { + // With <= 64 K-tiles the 64x64 1WG deep tile is faster. + if (one_wave && deep_enough && k_tiles <= 64 && (m % 64 == 0) && + (n % 64 == 0)) { + return kM64x64_1wgP14; + } + return kPair128x64P18; + } + } + + // ---- 128xN base ------------------------------------------------------ + return pick_tn == 256 + ? kM128x256 + : (pick_tn == 128 ? kM128x128 + : (pick_tn == 64 ? kM128x64 : kM128x32)); +} + +// m < 128 without SwapAB (SkipSwapForThinM): KBlockM=64 tiles give ceil(n/32) +// CTAs; 64x32 if it fits one wave, else 64x64. +inline int SelectThinMTile(int m, int n, int k, int target) { + const int nt32 = CeilDiv(n, 32); + const int mt = CeilDiv(m, 64); + if (n % 32 == 0 && nt32 * mt <= target) { + return UseDeepPipeline(k) ? kM64x32_1wgP18 : kM64x32_1wg; + } + return UseDeepPipeline(k) ? kM64x64_1wgP14 : kM64x64_1wg; +} + +// m < 128 with SwapAB: the weight (N x K) becomes the MMA's A (M-dim 128), +// the activation (M x K) the MMA's B (N-dim). +inline int SelectSwapABTile(int m, int n, int k, int target) { + if (n % 128 != 0 || m % 64 != 0 || k % 64 != 0) { + return -1; + } + // KBlockK=128 from k >= 8192. + if (k % 128 == 0 && k >= 8192) { + return kSwap128x64K128; + } + // 256-wide pair tile when the 128-wide grid exceeds 2 waves. + const int tiles128 = CeilDiv(n, 128) * CeilDiv(m, 64); + if ((n % 256 == 0) && tiles128 > 2 * target) { + return kSwap256x64Pair; + } + // KBlockN=32 if that still fits one wave. + if (CeilDiv(n, 128) * CeilDiv(m, 32) <= target) { + return kSwap128x32; + } + return kSwap128x64; +} + +// The dense ladder; -1 when no tile supports the shape. +inline int SelectBF16Cfg(int m, int n, int k, int sm_count) { + const int target = ResolveSmCount(sm_count); + if (m >= 4096) { + return SelectLargeMTile(m, n, k, target); + } + if (m >= 128) { + return SelectMidMTile(m, n, k, target); + } + if (SkipSwapForThinM(m, n, k, sm_count)) { + return SelectThinMTile(m, n, k, target); + } + return SelectSwapABTile(m, n, k, target); +} + +// ---- Grouped / batch ------------------------------------------------------- + +// Ids into kBF16ContiguousTiles (gemm_tile.cuh). +enum ContiguousTile : int { + kContPair256x256, // 256x256 pair, 7 stages + kContPair256x128, // 256x128 pair, 9 stages + kContM128x256, // 128x256, 16 overlap cols + kContM128x128, // 128x128, 6 stages + kContM128x64, // 128x64, 16 overlap cols + kContSwap128x64, +}; +static_assert(kContSwap128x64 + 1 == + static_cast(kBF16ContiguousTiles.size()), + "BF16 contiguous tile table and enum drifted apart"); + +// m is the total token count. +inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { + if (m >= 4096) { + return kContPair256x256; + } + if (m >= 128) { + // M stays 128 (the 1-CTA MMA requires M == 128); step finer on N + // only while the coarser tile underfills the grid. + const int target = ResolveSmCount(sm_count); + auto tiles = [&](int tm, int tn) { + return CeilDiv(m, tm) * CeilDiv(n, tn); + }; + // 2-CTA pair-UMMA first: weight TMA-multicast across the pair. Each + // cluster spans 2 SMs, so require clusters * 2 >= target. + const int clusters = CeilDiv(m, 256) * CeilDiv(n, 256); + if (m % 256 == 0 && n % 256 == 0 && k % 64 == 0 && + clusters * 2 >= target) { + // 256x128 frees a deeper pipeline; it pays only when 256x256 is + // lightly oversubscribed (<= ~2 waves). + const bool square_like = (n % 128 == 0) && (clusters <= 2 * target); + return square_like ? kContPair256x128 : kContPair256x256; + } + // 128x64 only on a <= 1-wave fit: halving N doubles the M*K panel + // reloads (costly on DRAM-bound mid-M). + if (tiles(128, 256) < target && (n % 128 == 0)) { + if (tiles(128, 64) <= target && (n % 64 == 0)) { + return kContM128x64; + } + return kContM128x128; + } + return kContM128x256; + } + return kContSwap128x64; +} + +// Ids into kBF16MaskedTiles (gemm_tile.cuh). +enum MaskedTile : int { + kMaskM128x256, // 128x256, 16 overlap cols + kMaskSwap128x64, + kMaskM128x128, // 128x128, 6 stages + kMaskM128x64, // 128x64, 16 overlap cols + kMaskPair256x256, // 256x256 pair, 7 stages + kMaskPair256x128, // 256x128 pair, 9 stages +}; +static_assert(kMaskPair256x128 + 1 == static_cast(kBF16MaskedTiles.size()), + "BF16 masked tile table and enum drifted apart"); + +// Masked pads every expert to max_m_per_expert, so the grid scales with +// num_experts * ceil(max_m / tm) * ceil(n / tn). +inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, + int sm_count) { + if (mm >= 4096) { + return kMaskPair256x256; + } + if (mm >= 128) { + const int target = ResolveSmCount(sm_count); + auto tiles = [&](int tm, int tn) { + return num_experts * CeilDiv(mm, tm) * CeilDiv(n, tn); + }; + const int clusters = num_experts * CeilDiv(mm, 256) * CeilDiv(n, 256); + if (mm % 256 == 0 && n % 256 == 0 && k % 64 == 0 && + clusters * 2 >= target) { + const bool square_like = (n % 128 == 0) && (clusters <= 2 * target); + return square_like ? kMaskPair256x128 : kMaskPair256x256; + } + // Keep 128x256 (best B-reuse) unless it underfills the grid; a + // blanket 128x128 preference regresses oversubscribed mid-M. + if (tiles(128, 256) < target && (n % 128 == 0)) { + if (tiles(128, 64) <= target && (n % 64 == 0)) { + return kMaskM128x64; + } + return kMaskM128x128; + } + return kMaskM128x256; + } + return kMaskSwap128x64; +} + +// Ids into kBF16BatchTiles (gemm_tile.cuh). +enum BatchTile : int { + kBatchPair256x256, // 256x256 pair, 6 stages + kBatchM128x256, // 128x256, 16 overlap cols + kBatchSwap128x64, +}; +static_assert(kBatchSwap128x64 + 1 == static_cast(kBF16BatchTiles.size()), + "BF16 batch tile table and enum drifted apart"); + +// Pure alignment ladder (no runtime SM reasoning); m is one item's rows. +inline int SelectBF16BatchCfg(int m, int n, int k) { + if (m % 256 == 0 && n % 256 == 0) { + return kBatchPair256x256; + } + if (m % 128 == 0 && n % 256 == 0) { + return kBatchM128x256; + } + if (m % 64 == 0 && n % 128 == 0) { + return kBatchSwap128x64; + } + return -1; +} + +// ---- Tile tables as launcher policies -------------------------------------- + +struct DenseTiles { + static constexpr const auto& tiles = kBF16DenseTiles; +}; +struct ContiguousTiles { + static constexpr const auto& tiles = kBF16ContiguousTiles; +}; +struct MaskedTiles { + static constexpr const auto& tiles = kBF16MaskedTiles; +}; +struct BatchTiles { + static constexpr const auto& tiles = kBF16BatchTiles; +}; + +// Divisibility contract of a selected tile: the output M/N tile multiples +// (N relaxes to %64 for predicated tails and %32 for non-power-of-2 widths), +// K a KBlockK multiple. SwapAB swaps the roles: KBlockM tiles the weight +// (output N), KBlockN the activation (output M). +inline void CheckBF16TileShape(const char* what, const TileSpec& t, int m, + int n, int k) { + const int n_mod = + t.force_ntail ? 64 + : (((t.block_n & (t.block_n - 1)) != 0) ? 32 : t.block_n); + const int m_div = t.swap_ab ? t.block_n : t.block_m; + const int n_div = t.swap_ab ? t.block_m : n_mod; + TORCH_CHECK(m % m_div == 0, what, " requires M to be divisible by ", m_div, + ", got ", m); + TORCH_CHECK(n % n_div == 0, what, " requires N to be divisible by ", n_div, + ", got ", n); + TORCH_CHECK(k % t.block_k == 0, what, " requires K to be divisible by ", + t.block_k, ", got ", k); +} + +template +inline void LaunchSelected(int cfg, const char* what, int m_check, + GemmParams& params, int sm_count, + cudaStream_t stream) { + CheckBF16TileShape(what, Tiles::tiles[cfg], m_check, params.n, params.k); + const GemmShape shape = {.m = params.m, + .n = params.n, + .k = params.k, + .m_grid = params.m, + .sm_count = sm_count, + .has_bias = false}; + kTileLaunchers[cfg]( + params, shape, stream); +} + +// Selects, validates and launches. The .cu mode branches call these. +inline void LaunchDense(GemmParams& params, int sm_count, cudaStream_t stream) { + const int cfg = SelectBF16Cfg(params.m, params.n, params.k, sm_count); + TORCH_CHECK(cfg >= 0, "No BF16 dense GEMM tile supports M=", params.m, + ", N=", params.n, ", K=", params.k); + LaunchSelected( + cfg, "BF16 dense GEMM", params.m, params, sm_count, stream); +} + +inline void LaunchContiguous(GemmParams& params, int sm_count, + cudaStream_t stream) { + const int cfg = + SelectBF16ContiguousCfg(params.m, params.n, params.k, sm_count); + TORCH_CHECK(cfg >= 0, + "bf16 contiguous GEMM: unsupported shape M=", params.m, + " N=", params.n, " K=", params.k); + LaunchSelected( + cfg, "bf16 contiguous GEMM", params.m, params, sm_count, stream); +} + +inline void LaunchMasked(GemmParams& params, int sm_count, + cudaStream_t stream) { + const int cfg = + SelectBF16MaskedCfg(params.num_experts, params.max_m_per_expert, + params.n, params.k, sm_count); + TORCH_CHECK(cfg >= 0, + "bf16 masked GEMM: unsupported shape E=", params.num_experts, + " max_m_per_expert=", params.max_m_per_expert, " N=", params.n, + " K=", params.k); + LaunchSelected(cfg, "bf16 masked GEMM", + params.max_m_per_expert, + params, sm_count, stream); +} + +inline void LaunchBatch(GemmParams& params, int sm_count, cudaStream_t stream) { + const int cfg = + SelectBF16BatchCfg(params.max_m_per_expert, params.n, params.k); + TORCH_CHECK( + cfg >= 0, "bf16 batch GEMM: unsupported shape B=", params.num_experts, + " M=", params.max_m_per_expert, " N=", params.n, " K=", params.k, + ". Need one of: (M%256==0 && N%256==0), " + "(M%128==0 && N%256==0), or (M%64==0 && N%128==0)."); + LaunchSelected(cfg, "bf16 batch GEMM", + params.max_m_per_expert, + params, sm_count, stream); +} + +} // namespace bf16 } // namespace halops diff --git a/csrc/kernel/gemm/gemm_tile.cuh b/csrc/kernel/gemm/gemm_tile.cuh index 37ead35..5bf1b1b 100644 --- a/csrc/kernel/gemm/gemm_tile.cuh +++ b/csrc/kernel/gemm/gemm_tile.cuh @@ -100,10 +100,12 @@ struct TileSpec { bool bias = false; // AddBias // Dispatch policy, not kernel parameters. - bool dense_only = false; // only tuned/allowed for the dense launcher - bool batch = false; // a dense_only tile also tuned for batch - bool searchable = true; // may the cost model pick it? + bool dense_only = false; // only tuned/allowed for the dense launcher + bool batch = false; // a dense_only tile also tuned for batch + bool searchable = true; // may the cost model pick it? int quant_stages = 0; + int epi_warp_groups = 0; // KEpilogueWarpGroupsOverride; 0 = auto + bool force_ntail = false; // KForceEpiNPredicate (predicated N-tail store) constexpr bool pair() const { return cluster_m * cluster_n > 1; } // Activation-tile rows/cols; SwapAB swaps the two MMA dimensions. @@ -187,6 +189,21 @@ struct MmaTraits { static constexpr const char* kName = "w4a8-mxfp4"; }; +template <> +struct MmaTraits { + using Operand = cutlass::bfloat16_t; + using OperandA = Operand; + using OperandB = Operand; + using Output = cutlass::bfloat16_t; + // Placeholder only: BF16 has no scale factors and never dereferences + // the SF pointer. + using Scale = cutlass::float_ue8m0_t; + static constexpr bool kFp4 = false; + static constexpr int kSfVecSize = 16; + static constexpr bool kHasAlpha = false; + static constexpr const char* kName = "bf16"; +}; + template using MakeTile = @@ -194,7 +211,8 @@ using MakeTile = S.cluster_m, S.cluster_n, S.tmem_overlap, S.epi_regs, S.swizzle, S.skip_fence, S.swap_ab, MmaTraits::kFp4, MmaTraits::kSfVecSize, MmaTraits::kHasAlpha, S.bias, - Mode, Op>; + Mode, Op, S.epi_warp_groups, S.force_ntail, + Kind == MmaKind::BF16>; // Fp8 constexpr TileSpec kFp8_128x256 = {.block_m = 128, @@ -459,214 +477,270 @@ struct CandidateTiles { }; // =========================================================================== -// BF16 (kind::f16) configs — no block-scale, no alpha. KBlockK=64 gives the -// same per-stage A/B smem as FP8@KBlockK=128 and there is no SFA/SFB smem, so -// stage counts can mirror the FP8 configs (< 228 KB). The tail three template -// parameters are BF16-relevant: EWGO (KEpilogueWarpGroupsOverride, 1 for the -// 2SM "2x2" TMEM layout and narrow tiles), NTAIL (KForceEpiNPredicate, the -// predicated store for N % KBlockN != 0), BF16 (KIsBF16). +// BF16 tiles — no block-scale, no alpha. KBlockK=64 gives the same per-stage +// A/B smem as FP8@KBlockK=128 and there is no SFA/SFB smem, so stage counts +// can mirror the FP8 configs. epi_warp_groups=1 marks the 1-epilogue-warp- +// group layouts (narrow tiles, 2SM "2x2" TMEM layout); force_ntail marks the +// predicated N-tail store (N only has to divide 64, or 32 for non-power-of-2 +// widths). dense_only stays false on every BF16 tile: each mode picks from +// its own table below, so the flag is never consulted. +// +// Dense table. Order defines the id the dense selector returns +// (SelectBF16Cfg in gemm_dispatch.cuh); keep the two in sync. +// --------------------------------------------------------------------------- +constexpr TileSpec kBF16_256x256_pair = {.block_m = 256, + .block_n = 256, + .block_k = 64, + .main_stages = 6, + .cluster_m = 2}; +constexpr TileSpec kBF16_256x256_pair_p7 = {.block_m = 256, + .block_n = 256, + .block_k = 64, + .main_stages = 7, + .cluster_m = 2}; +constexpr TileSpec kBF16_256x128_pair = {.block_m = 256, + .block_n = 128, + .block_k = 64, + .main_stages = 8, + .cluster_m = 2}; +constexpr TileSpec kBF16_256x128_pair_ntail = {.block_m = 256, + .block_n = 128, + .block_k = 64, + .main_stages = 8, + .cluster_m = 2, + .force_ntail = true}; +constexpr TileSpec kBF16_256x128_pair_p9 = {.block_m = 256, + .block_n = 128, + .block_k = 64, + .main_stages = 9, + .cluster_m = 2}; +constexpr TileSpec kBF16_256x128_pair_p9_ntail = {.block_m = 256, + .block_n = 128, + .block_k = 64, + .main_stages = 9, + .cluster_m = 2, + .force_ntail = true}; +constexpr TileSpec kBF16_256x192_pair = {.block_m = 256, + .block_n = 192, + .block_k = 64, + .main_stages = 8, + .cluster_m = 2}; +constexpr TileSpec kBF16_256x64_pair = {.block_m = 256, + .block_n = 64, + .block_k = 64, + .main_stages = 10, + .cluster_m = 2}; +constexpr TileSpec kBF16_128x256 = { + .block_m = 128, .block_n = 256, .block_k = 64, .main_stages = 4}; +constexpr TileSpec kBF16_128x128 = { + .block_m = 128, .block_n = 128, .block_k = 64, .main_stages = 4}; +constexpr TileSpec kBF16_128x64 = { + .block_m = 128, .block_n = 64, .block_k = 64, .main_stages = 8}; +constexpr TileSpec kBF16_128x32 = { + .block_m = 128, .block_n = 32, .block_k = 64, .main_stages = 10}; +constexpr TileSpec kBF16_128x64_pair_p18 = {.block_m = 128, + .block_n = 64, + .block_k = 64, + .main_stages = 18, + .cluster_m = 2, + .epi_warp_groups = 1}; +constexpr TileSpec kBF16_64x128 = { + .block_m = 64, .block_n = 128, .block_k = 64, .main_stages = 8}; +constexpr TileSpec kBF16_64x96_p11 = {.block_m = 64, + .block_n = 96, + .block_k = 64, + .main_stages = 11, + .epi_warp_groups = 1}; +constexpr TileSpec kBF16_64x224 = {.block_m = 64, + .block_n = 224, + .block_k = 64, + .main_stages = 6, + .epi_warp_groups = 1}; +constexpr TileSpec kBF16_64x64 = { + .block_m = 64, .block_n = 64, .block_k = 64, .main_stages = 10}; +constexpr TileSpec kBF16_64x64_1wg = {.block_m = 64, + .block_n = 64, + .block_k = 64, + .main_stages = 10, + .epi_warp_groups = 1}; +constexpr TileSpec kBF16_64x64_1wg_p14 = {.block_m = 64, + .block_n = 64, + .block_k = 64, + .main_stages = 14, + .epi_warp_groups = 1}; +constexpr TileSpec kBF16_64x32_1wg = {.block_m = 64, + .block_n = 32, + .block_k = 64, + .main_stages = 10, + .epi_warp_groups = 1}; +constexpr TileSpec kBF16_64x32_1wg_p18 = {.block_m = 64, + .block_n = 32, + .block_k = 64, + .main_stages = 18, + .epi_warp_groups = 1}; +constexpr TileSpec kBF16_128x64_swap = {.block_m = 128, + .block_n = 64, + .block_k = 64, + .main_stages = 8, + .swap_ab = true}; +constexpr TileSpec kBF16_128x32_swap = {.block_m = 128, + .block_n = 32, + .block_k = 64, + .main_stages = 8, + .swap_ab = true}; +constexpr TileSpec kBF16_256x64_swap_pair = {.block_m = 256, + .block_n = 64, + .block_k = 64, + .main_stages = 9, + .cluster_m = 2, + .swap_ab = true}; +constexpr TileSpec kBF16_128x64x128_swap = {.block_m = 128, + .block_n = 64, + .block_k = 128, + .main_stages = 4, + .swap_ab = true}; + +inline constexpr std::array kBF16DenseTiles = { + kBF16_256x256_pair, kBF16_256x256_pair_p7, + kBF16_256x128_pair, kBF16_256x128_pair_ntail, + kBF16_256x128_pair_p9, kBF16_256x128_pair_p9_ntail, + kBF16_256x192_pair, kBF16_256x64_pair, + kBF16_128x256, kBF16_128x128, + kBF16_128x64, kBF16_128x32, + kBF16_128x64_pair_p18, kBF16_64x128, + kBF16_64x96_p11, kBF16_64x224, + kBF16_64x64, kBF16_64x64_1wg, + kBF16_64x64_1wg_p14, kBF16_64x32_1wg, + kBF16_64x32_1wg_p18, kBF16_128x64_swap, + kBF16_128x32_swap, kBF16_256x64_swap_pair, + kBF16_128x64x128_swap, +}; + +// Grouped/batch tiles: deeper / TMEM-overlapped variants of the dense shapes. +constexpr TileSpec kBF16_128x256_ovlp16 = {.block_m = 128, + .block_n = 256, + .block_k = 64, + .main_stages = 4, + .tmem_overlap = 16}; +constexpr TileSpec kBF16_128x128_p6 = { + .block_m = 128, .block_n = 128, .block_k = 64, .main_stages = 6}; +constexpr TileSpec kBF16_128x64_ovlp16 = {.block_m = 128, + .block_n = 64, + .block_k = 64, + .main_stages = 8, + .tmem_overlap = 16}; + +// Order defines the id the per-mode selectors return (gemm_dispatch.cuh). +inline constexpr std::array kBF16ContiguousTiles = { + kBF16_256x256_pair_p7, // 0 + kBF16_256x128_pair_p9, // 1 + kBF16_128x256_ovlp16, // 2 + kBF16_128x128_p6, // 3 + kBF16_128x64_ovlp16, // 4 + kBF16_128x64_swap, // 5 +}; + +inline constexpr std::array kBF16MaskedTiles = { + kBF16_128x256_ovlp16, // 0 + kBF16_128x64_swap, // 1 + kBF16_128x128_p6, // 2 + kBF16_128x64_ovlp16, // 3 + kBF16_256x256_pair_p7, // 4 + kBF16_256x128_pair_p9, // 5 +}; + +inline constexpr std::array kBF16BatchTiles = { + kBF16_256x256_pair, // 0 + kBF16_128x256_ovlp16, // 1 + kBF16_128x64_swap, // 2 +}; + +// --------------------------------------------------------------------------- +// Field-lock asserts: guard the designated-initializer tables above against +// drift. These tables replaced hand-written GemmTile structs; the locks pin +// every kernel-facing constant a table entry must produce. // --------------------------------------------------------------------------- -// Dense (Naive) -using GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA = - GemmTile<256, 256, 64, 6, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x256x64_1CTA = - GemmTile<128, 256, 64, 4, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x128x64_1CTA = - GemmTile<128, 128, 64, 4, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x32x64_1CTA = - GemmTile<128, 32, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA = - GemmTile<128, 64, 64, 8, 2, 2, 2, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P16 = - GemmTile<128, 64, 64, 16, 2, 2, 2, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18 = - GemmTile<128, 64, 64, 18, 2, 2, 2, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x64_2CTA_P18 = - GemmTile<128, 64, 64, 18, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x96x64_1CTA_P11 = - GemmTile<64, 96, 64, 11, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x224x64_1CTA_P6 = - GemmTile<64, 224, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x64_2x1CTA = - GemmTile<128, 64, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x64x64_1CTA = - GemmTile<64, 64, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x128x64_1CTA = - GemmTile<64, 128, 64, 8, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P14_1CTA = - GemmTile<64, 32, 64, 14, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_P18_1CTA = - GemmTile<64, 32, 64, 18, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x32x64_1WG_1CTA = - GemmTile<64, 32, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_1CTA = - GemmTile<64, 64, 64, 10, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x64x64_P12_1CTA = - GemmTile<64, 64, 64, 12, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x64x64_P14_1CTA = - GemmTile<64, 64, 64, 14, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias64x64x64_1WG_P14_1CTA = - GemmTile<64, 64, 64, 14, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 1, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x32x64_P4_1CTA = - GemmTile<128, 32, 64, 4, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x32x64_P6_1CTA = - GemmTile<128, 32, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x32x32_1CTA = - GemmTile<128, 32, 32, 16, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x64_1CTA = - GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA = - GemmTile<256, 128, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail = - GemmTile<256, 128, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, true, true>; -using GemmKernelConfigBF16NaiveNoBias256x64x64_2CTA = - GemmTile<256, 64, 64, 10, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA_P7 = - GemmTile<256, 256, 64, 7, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9 = - GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail = - GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, true, true>; -using GemmKernelConfigBF16NaiveNoBias256x192x64_2CTA = - GemmTile<256, 192, 64, 8, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x64_SwapAB_1CTA = - GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x32x64_SwapAB_1CTA = - GemmTile<128, 32, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias256x64x64_SwapAB_2CTA = - GemmTile<256, 64, 64, 9, 2, 2, 1, 0, 208, false, false, true, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; -using GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA = - GemmTile<128, 64, 128, 4, 2, 1, 1, 0, 208, false, false, true, false, 16, - false, false, KernelMode::Dense, EpilogueOp::Identity, 0, false, true>; - -// Batch -using GemmKernelConfigBF16BatchNoBias256x256x64_2CTA = - GemmTile<256, 256, 64, 6, 2, 2, 1, 16, 208, false, false, false, false, 16, - false, false, KernelMode::Batch, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16BatchNoBias128x256x64_1CTA = - GemmTile<128, 256, 64, 4, 2, 1, 1, 16, 208, false, false, false, false, 16, - false, false, KernelMode::Batch, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16BatchNoBias128x64x64_SwapAB_1CTA = - GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, - false, false, KernelMode::Batch, EpilogueOp::Identity, 0, false, true>; - -// Group contiguous -using GemmKernelConfigBF16ContiguousNoBias256x256x64_2CTA = - GemmTile<256, 256, 64, 7, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16ContiguousNoBias256x128x64_2CTA = - GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16ContiguousNoBias128x256x64_1CTA = - GemmTile<128, 256, 64, 4, 2, 1, 1, 16, 208, false, false, false, false, 16, - false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16ContiguousNoBias128x128x64_1CTA = - GemmTile<128, 128, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16ContiguousNoBias128x64x64_1CTA = - GemmTile<128, 64, 64, 8, 2, 1, 1, 16, 208, false, false, false, false, 16, - false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16ContiguousNoBias128x64x64_SwapAB_1CTA = - GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, - false, false, KernelMode::Contiguous, EpilogueOp::Identity, 0, false, true>; - -// Group masked -using GemmKernelConfigBF16MaskedNoBias128x256x64_1CTA = - GemmTile<128, 256, 64, 4, 2, 1, 1, 16, 208, false, false, false, false, 16, - false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16MaskedNoBias128x64x64_SwapAB_1CTA = - GemmTile<128, 64, 64, 8, 2, 1, 1, 0, 208, false, false, true, false, 16, - false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16MaskedNoBias128x128x64_1CTA = - GemmTile<128, 128, 64, 6, 2, 1, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16MaskedNoBias128x64x64_1CTA = - GemmTile<128, 64, 64, 8, 2, 1, 1, 16, 208, false, false, false, false, 16, - false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16MaskedNoBias256x256x64_2CTA = - GemmTile<256, 256, 64, 7, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; - -using GemmKernelConfigBF16MaskedNoBias256x128x64_2CTA = - GemmTile<256, 128, 64, 9, 2, 2, 1, 0, 208, false, false, false, false, 16, - false, false, KernelMode::Masked, EpilogueOp::Identity, 0, false, true>; - -// Field-lock asserts: guard against positional-argument drift in the -// 21-parameter alias lists above (migration from hand-written structs). -static_assert(GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KBlockM == 256 && - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KBlockN == 256 && - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KBlockK == 64 && - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KPrologueStages == - 6 && - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::IsPairUmma && - GemmKernelConfigBF16NaiveNoBias256x256x64_2CTA::KIsBF16); +template +constexpr bool BF16TileLocks() { + using C = MakeTile; + return C::KBlockM == BM && C::KBlockN == BN && C::KBlockK == BK && + C::KPrologueStages == ST && C::KClusterM == CM && + C::KClusterN == CN && C::KTmemOverlapCols == OVLP && + C::KNumRegsEpilogue == 208 && + C::KEpilogueWarpGroupsOverride == EWGO && C::SwapAB == SWAP && + C::KForceEpiNPredicate == NTAIL && C::KIsBF16 && !C::KIsFP4 && + !C::HasAlpha && !C::AddBias && !C::UseTileSwizzle && + !C::SkipTmemFence; +} + +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert( + BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert( + BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); static_assert( - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail::KForceEpiNPredicate && - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_Ntail::KPrologueStages == - 8 && - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail::KPrologueStages == - 9 && - GemmKernelConfigBF16NaiveNoBias256x128x64_2CTA_P9_Ntail:: - KForceEpiNPredicate); + BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); static_assert( - GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18:: - KEpilogueWarpGroupsOverride == 1 && - GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18::KPrologueStages == - 18 && - GemmKernelConfigBF16NaiveNoBias128x64x64_2x2CTA_P18::KClusterN == 2); -static_assert(GemmKernelConfigBF16NaiveNoBias128x32x32_1CTA::KBlockK == 32 && - GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA::KBlockK == - 128 && - GemmKernelConfigBF16NaiveNoBias128x64x128_SwapAB_1CTA::SwapAB); + BF16TileLocks()); static_assert( - GemmKernelConfigBF16ContiguousNoBias128x256x64_1CTA::KTmemOverlapCols == - 16 && - GemmKernelConfigBF16MaskedNoBias256x128x64_2CTA::KPrologueStages == 9 && - GemmKernelConfigBF16BatchNoBias128x64x64_SwapAB_1CTA::SwapAB); + BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); +static_assert(BF16TileLocks()); } // namespace halops diff --git a/csrc/kernel/gemm/group_contiguous_gemm.cu b/csrc/kernel/gemm/group_contiguous_gemm.cu index 5e4b756..28adc27 100644 --- a/csrc/kernel/gemm/group_contiguous_gemm.cu +++ b/csrc/kernel/gemm/group_contiguous_gemm.cu @@ -15,7 +15,6 @@ #include #include -#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -67,13 +66,8 @@ void GroupContiguousGemm(const torch::Tensor& input, params.use_pdl = true; if (mode == "bf16") { - using TypeA = cutlass::bfloat16_t; - using TypeB = cutlass::bfloat16_t; - using TypeC = cutlass::bfloat16_t; - using TypeD = cutlass::bfloat16_t; - using TypeSF = cutlass::float_ue8m0_t; // placeholder, unused - using TypeAccumulate = float; - + // Native BF16: sfa/sfb/bias/alpha are ignored; dispatch and launch + // live in gemm_dispatch.cuh (bf16::LaunchContiguous). const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -90,20 +84,7 @@ void GroupContiguousGemm(const torch::Tensor& input, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - - const int cfg = bf16_dispatch::SelectBF16ContiguousCfg(m, n, k, sm); - TORCH_CHECK(cfg >= 0, "bf16 contiguous GEMM: unsupported shape M=", m, - " N=", n, " K=", k); - bf16_dispatch::CheckBF16CfgShape( - "bf16 contiguous GEMM", bf16_dispatch::kBF16ContiguousCfgs[cfg], m, - n, k); - bf16_dispatch::DispatchBF16SmallCfg< - bf16_dispatch::BF16ContiguousTiles, - bf16_dispatch::kBF16ContiguousCount>( - cfg, "bf16 contiguous", [&]() { - gemm_impl(params, sm, stream); - }); + bf16::LaunchContiguous(params, sm, stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 contiguous grouped GEMM requires sfa/sfb " @@ -132,6 +113,9 @@ void GroupContiguousGemm(const torch::Tensor& input, .has_bias = bias.has_value()}, stream); } else if (mode == "w4a8-mxfp4") { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "w4a8-mxfp4 grouped GEMM requires sfa/sfb scale factors " + "(only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(2) * 2; // 2 FP4 per packed byte TORCH_CHECK(input.size(1) == k, "W4A8 input K (unpacked fp8) must match unpacked weight K, " @@ -140,16 +124,16 @@ void GroupContiguousGemm(const torch::Tensor& input, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); TORCH_CHECK(!bias.has_value(), "W4A8 mode does not support bias yet."); TORCH_CHECK( !alpha.has_value(), "W4A8 mode does not take alpha; scales are per-group UE8M0."); const int sf_k = k / 32; // UE8M0 group-32 scale on both A and B - TORCH_CHECK(sfa.size(-1) == sf_k && sfb.size(-1) == sf_k, + TORCH_CHECK(sfa->size(-1) == sf_k && sfb->size(-1) == sf_k, "W4A8 'w4a8-mxfp4' (UE8M0 per 32) requires SF K = ", sf_k, - ", got sfa K=", sfa.size(-1), " and sfb K=", sfb.size(-1), + ", got sfa K=", sfa->size(-1), " and sfb K=", sfb->size(-1), "."); LaunchCfg( params, diff --git a/csrc/kernel/gemm/group_masked_gemm.cu b/csrc/kernel/gemm/group_masked_gemm.cu index 33539b2..b934823 100644 --- a/csrc/kernel/gemm/group_masked_gemm.cu +++ b/csrc/kernel/gemm/group_masked_gemm.cu @@ -15,7 +15,6 @@ #include #include -#include "kernel/gemm/bf16_cfgs.h" #include "kernel/gemm/gemm_dispatch.cuh" #include "kernel/gemm/gemm_utils.h" @@ -76,13 +75,8 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.use_pdl = true; if (mode == "bf16") { - using TypeA = cutlass::bfloat16_t; - using TypeB = cutlass::bfloat16_t; - using TypeC = cutlass::bfloat16_t; - using TypeD = cutlass::bfloat16_t; - using TypeSF = cutlass::float_ue8m0_t; // placeholder, unused - using TypeAccumulate = float; - + // Native BF16: sfa/sfb/bias/alpha are ignored; dispatch and launch + // live in gemm_dispatch.cuh (bf16::LaunchMasked). const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -99,21 +93,7 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - - const int cfg = bf16_dispatch::SelectBF16MaskedCfg( - num_experts, max_m_per_expert, n, k, sm); - TORCH_CHECK(cfg >= 0, - "bf16 masked GEMM: unsupported shape E=", num_experts, - " max_m_per_expert=", max_m_per_expert, " N=", n, " K=", k); - bf16_dispatch::CheckBF16CfgShape("bf16 masked GEMM", - bf16_dispatch::kBF16MaskedCfgs[cfg], - max_m_per_expert, n, k); - bf16_dispatch::DispatchBF16SmallCfg( - cfg, "bf16 masked", [&]() { - gemm_impl(params, sm, stream); - }); + bf16::LaunchMasked(params, sm, stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 masked grouped GEMM requires sfa/sfb scale " @@ -140,6 +120,9 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, .has_bias = bias.has_value()}, stream); } else if (mode == "w4a8-mxfp4") { + TORCH_CHECK(sfa.has_value() && sfb.has_value(), + "w4a8-mxfp4 grouped GEMM requires sfa/sfb scale factors " + "(only mode='bf16' accepts sfa=None, sfb=None)"); const int k = weight.size(2) * 2; // 2 FP4 per packed byte TORCH_CHECK(input.size(1) == k, "W4A8 input K (unpacked fp8) must match unpacked weight K, " @@ -148,16 +131,16 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.k = k; params.ptr_a = input.data_ptr(); params.ptr_b = weight.data_ptr(); - params.ptr_sfa = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + params.ptr_sfa = sfa->data_ptr(); + params.ptr_sfb = sfb->data_ptr(); TORCH_CHECK(!bias.has_value(), "W4A8 mode does not support bias yet."); TORCH_CHECK( !alpha.has_value(), "W4A8 mode does not take alpha; scales are per-group UE8M0."); const int sf_k = k / 32; // UE8M0 group-32 scale on both A and B - TORCH_CHECK(sfa.size(-1) == sf_k && sfb.size(-1) == sf_k, + TORCH_CHECK(sfa->size(-1) == sf_k && sfb->size(-1) == sf_k, "W4A8 'w4a8-mxfp4' (UE8M0 per 32) requires SF K = ", sf_k, - ", got sfa K=", sfa.size(-1), " and sfb K=", sfb.size(-1), + ", got sfa K=", sfa->size(-1), " and sfb K=", sfb->size(-1), "."); LaunchCfg(params, {.m = max_m_per_expert, From c55e51cbe8f2a72faa6f011212de488320b4c11a Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Fri, 6 Nov 2026 08:12:31 +0800 Subject: [PATCH 04/14] style(gemm): tighten the comments added with the BF16 GEMM commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review feedback on 8757ca2: the new comments read like prose. Trim every comment that commit introduced — one or two lines per block, no bullet lists or rhetorical section headers, no restating what the code does. Technical facts (atom layouts, TMEM constraints, measured error numbers) are kept; wording only. Files: kernel_traits.cuh, tile_scheduler.cuh, mainloop_fwd.cuh, gemm_kernel.cuh, epilogue.cuh, stream_k_reduce.cuh, utils.cuh, gemm_utils.h, gemm_tile.cuh (parameter legend) and the two BF16 tests. Also drops one stale pointer in utils.cuh (BF16 tiles now live in gemm_tile.cuh) and a leftover reference to the deleted HALOPS_STREAMK switch. Verified: bf16 dense/batch/grouped tests and the quantized dense/batch/ contiguous/masked suites all pass (109 passed). Co-Authored-By: Claude Code --- csrc/kernel/gemm/epilogue.cuh | 37 +++--- csrc/kernel/gemm/gemm_kernel.cuh | 58 ++++----- csrc/kernel/gemm/gemm_tile.cuh | 7 +- csrc/kernel/gemm/gemm_utils.h | 6 +- csrc/kernel/gemm/kernel_traits.cuh | 173 ++++++++++----------------- csrc/kernel/gemm/mainloop_fwd.cuh | 49 +++----- csrc/kernel/gemm/stream_k_reduce.cuh | 27 ++--- csrc/kernel/gemm/tile_scheduler.cuh | 172 +++++++++++--------------- csrc/kernel/gemm/utils.cuh | 10 +- tests/test_gemm_bf16.py | 18 +-- tests/test_gemm_bf16_grouped.py | 15 ++- 11 files changed, 222 insertions(+), 350 deletions(-) diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index 2032ac8..868577b 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -97,9 +97,8 @@ class CollectiveEpilogue { int rows_per_batch = 0; SituCoef situ{}; int64_t gate_ld = 0; - // Tail-only stream-K: fp32 partial workspace, laid out as - // [slot][CtaShape_M][KBlockN] (slot = scheduler.partial_slot()) - // nullptr when stream-K is off. + // Stream-K fp32 partial workspace: [slot][CtaShape_M][KBlockN]; null + // when stream-K is off. TypeAccumulate* ptr_partial = nullptr; }; @@ -724,9 +723,8 @@ class CollectiveEpilogue { // BF16 path: TMEM -> registers -> cast -> GMEM through CuTe tiled copies, // which follow the 16dp (64-row CTA) and 2SM "2x2" accumulator layouts. - // KStreamK: tail-only stream-K instantiation. Compile-time so the - // data-parallel store path keeps its register allocation (a runtime branch - // here causes heavy spills). + // KStreamK: compile-time stream-K instantiation; a runtime branch here + // would spill the data-parallel store path. template CUTLASS_DEVICE void epilogue_bf16(Params const& epilogue_params, AccumulatorPipeline& acc_pipeline, @@ -831,18 +829,15 @@ class CollectiveEpilogue { return thr_r2g_sub.partition_D(gD_sub_tile_coords); }(); - // Tail-only stream-K: partials address a compact per-CTA - // [CtaShape_M][KBlockN] fp32 slot instead of the global D grid. + // Stream-K: partials address a compact per-CTA [CtaShape_M][KBlockN] + // slot instead of the global D grid. static constexpr int KPartialM = cute::size<0>(cute::take<0, 2>(CtaShape_MNK{})); static constexpr int KPartialN = cute::size<1>(cute::take<0, 2>(CtaShape_MNK{})); - // Loop-invariant partial-store partition, built once against the - // workspace base rather than in r2g_sub (inlined per sub-tile; doing it - // there causes spills). Per work item only a pointer offset changes. - // Same thread layout as the D store -> vectorized fp32 stores. Empty - // tuple when !KStreamK so data-parallel codegen is untouched. + // Built once against the workspace base (doing it in r2g_sub causes + // spills); same thread layout as the D store. Empty when !KStreamK. auto partial_store = [&]() { if constexpr (KStreamK) { auto tiled_p = cute::make_tiled_copy_D( @@ -874,8 +869,7 @@ class CollectiveEpilogue { while (scheduler.is_valid()) { uint32_t m_idx = scheduler.m_idx(); uint32_t n_idx = scheduler.n_idx(); - // Resolved once per work item: < 0 means it owns the whole K range - // and stores the final bf16 result. + // Resolved per work item: < 0 stores the final bf16 result. int partial_slot = -1; int64_t partial_off = 0; if constexpr (KStreamK) { @@ -911,11 +905,9 @@ class CollectiveEpilogue { auto r2g_sub = [&](uint32_t epi_m_idx, uint32_t sub_n_idx) { // N-overhang predicate: a KBlockN that does not divide n - // overhangs on the last tile. D is stored register -> GMEM - // (SM100_STORE_256bit, not TMA; CopyOpS2G is unused), so - // nothing clips OOB writes. The host enforces n % KSubTileN == - // 0, so each sub-tile is entirely in or out of bounds: one - // scalar compare, vector store intact. + // overhangs on the last tile, and D is stored register -> GMEM + // (not TMA), so nothing clips OOB writes. The host enforces + // n % KSubTileN == 0, so one compare covers a whole sub-tile. if constexpr (KernelTraits::KEpiNeedsNPredicate) { const uint32_t sub_n_begin = n_idx * static_cast(KernelTraits::KBlockN) + @@ -925,9 +917,8 @@ class CollectiveEpilogue { return; } } - // Stream-K tail chunk (K-slice only): store the raw fp32 - // accumulator to its workspace slot; the reduce kernel sums and - // casts. No alpha: stream-K is gated to no-alpha BF16 dense. + // Stream-K tail chunk: store the raw fp32 accumulator; the + // reduce kernel sums and casts. Stream-K is no-alpha only. if constexpr (KStreamK) { if (partial_slot >= 0) { auto dst_p = cute::get<2>(partial_store); diff --git a/csrc/kernel/gemm/gemm_kernel.cuh b/csrc/kernel/gemm/gemm_kernel.cuh index dff7499..f5f9db6 100644 --- a/csrc/kernel/gemm/gemm_kernel.cuh +++ b/csrc/kernel/gemm/gemm_kernel.cuh @@ -85,8 +85,8 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) bool is_load_ab_warp = (warp_idx == KernelTraits::KLoadABWarpId); - // Prefetch TMA descriptors: AB warp handles A, B (+ SFA, SFB for - // block-scaled modes). BF16 has no scale-factor descriptors. + // Prefetch TMA descriptors: the AB warp handles A and B (plus SFA/SFB for + // block-scaled modes). if (is_load_ab_warp && lane_predicate) { cute::prefetch_tma_descriptor( mainloop_params.tma_load_A.get_tma_descriptor()); @@ -199,12 +199,10 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) BiasPipeline bias_pipeline(shared_storage.bias_pipeline, bias_pipeline_params); - // TMEM allocation, issued right before the barrier that waits on it - // (hoisting it earlier hides nothing). + // TMEM allocation, issued right before the barrier that waits on it. TmemAllocator tmem_allocator{}; if (warp_idx == KernelTraits::KMmaWarpId) { - // Right-sized (KTmemColumns, see kernel_traits.cuh), not the full 512 - // columns; shrinks the TMEM footprint, MMA geometry unchanged. + // Right-sized (KTmemColumns), not the full 512 columns. tmem_allocator.allocate(KernelTraits::KTmemColumns, &shared_storage.tmem_base_ptr); } @@ -230,16 +228,14 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) } TmemStorage tmem_storage = main_loop.init_tmem_tensors(); - // The load warp never touches TMEM, so it skips set_tmem_offsets and with - // it the first tmem_base_ptr read (where tcgen05.alloc latency surfaces), - // reaching its first TMA issue earlier. + // The load warp skips set_tmem_offsets and the first tmem_base_ptr read + // (where alloc latency surfaces). if (!is_load_ab_warp) { main_loop.set_tmem_offsets(tmem_storage, shared_storage.tmem_base_ptr); } if (is_load_ab_warp) { - // Prologue warps need few registers — release to pool for epilogue - // warps. + // Prologue warps release registers to the pool. if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } @@ -263,16 +259,15 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } - // Guarded so the rewriter (which static_asserts IsSfbRowShift) is not - // instantiated by every other config. + // Guarded so the rewriter (static_asserts IsSfbRowShift) is not + // instantiated elsewhere. if constexpr (KernelTraits::IsSfbRowShift) { main_loop.sfb_shift_rows( mainloop_params, shared_storage, scheduler, warp_idx - KernelTraits::KSfbTransposeWarpId); } } else if (warp_idx <= KernelTraits::KEpilogueWarpEndId) { - // Epilogue warps need the most registers for TMEM->reg->smem - // conversion. + // Epilogue warps need the most registers. if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_alloc< KernelTraits::KNumRegsEpilogue>(); @@ -302,7 +297,7 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) __syncthreads(); } - // Then deallocate TMEM (must match the allocated column count). + // Deallocate TMEM (must match the allocated column count). if (warp_idx == KernelTraits::KMmaWarpId) { tmem_allocator.release_allocation_lock(); tmem_allocator.free(shared_storage.tmem_base_ptr, @@ -451,15 +446,15 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, "gemm_impl requires M to be divisible by KBlockM=", KernelTraits::KBlockM, ", got ", params.m); if constexpr (KernelTraits::IsSfbUnaligned) { - // Unpacked 224-pair tiles load a run of whole 128-row SF - // atoms, which requires n to tile cleanly at 128. + // Unpacked 224-pair tiles load whole 128-row SF atoms, so n + // must tile at 128. TORCH_CHECK(params.n % 128 == 0 && params.n >= 384, "gemm_impl requires N to be a multiple of 128 and " ">= 384 for KBlockN=", KernelTraits::KBlockN, ", got ", params.n); } else if constexpr (KernelTraits::KEpiNeedsNPredicate) { // Non-power-of-2 KBlockN (96/112/224) need not divide n; the - // epilogue predicates the overhang per KSubTileN sub-tile. + // overhang is predicated per sub-tile. TORCH_CHECK(params.n % KernelTraits::KSubTileN == 0, "gemm_impl with KBlockN=", KernelTraits::KBlockN, " predicates the N overhang per ", @@ -484,8 +479,7 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, } } -// Kernel pointer in, not a traits type: the caller picks between the -// data-parallel and the stream-K instantiation of gemm_kernel. +// Kernel-pointer launch: the caller picks data-parallel or stream-K. template void LaunchGemmKernel(void const* kernel_ptr, dim3 dim_grid, dim3 dim_cluster, @@ -525,8 +519,7 @@ void gemm_impl_body(GemmParams& params, const int sm_count, static constexpr int KCTAsPerCluster = cute::size(ClusterShape_MNK{}); // Same SM-count resolution as the dispatch-site tile heuristics. const int raw_sm_count = ResolveSmCount(sm_count); - // Round down to a multiple of KCTAsPerCluster so every cluster is fully - // occupied. + // Round down to a multiple of KCTAsPerCluster. const int runtime_sm_count = (raw_sm_count / KCTAsPerCluster) * KCTAsPerCluster; int M = params.m; @@ -562,9 +555,8 @@ void gemm_impl_body(GemmParams& params, const int sm_count, cute::Layout layout_C = cute::make_layout( cute::make_shape(M, N), cute::make_stride(N, cute::Int<1>{})); - // The scale tensors always cover whole 128-row SfAtom atoms even when the - // activation is only M rows. (BF16 passes null SF pointers; these layouts - // are then unused bookkeeping.) + // Scale tensors cover whole 128-row SfAtom atoms even for M < 128 rows + // (unused for BF16). const int M_sf = AlignSfM(M); typename KernelTraits::LayoutSFA layout_SFA = SwapAB ? KernelTraits::Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA( @@ -601,8 +593,8 @@ void gemm_impl_body(GemmParams& params, const int sm_count, params.masked_m, params.expert_ids, num_clusters_planned, k_tiles_planned); - // Tail-only stream-K fp32 workspace, allocated only if the scheduler split - // a tail: rem * splits * KNumCTA per-CTA slots of CtaShape_M x KBlockN. + // Stream-K fp32 workspace, allocated only when a tail was split: + // rem * splits * KNumCTA slots of CtaShape_M x KBlockN. static constexpr int KPartM = KernelTraits::KBlockM / KernelTraits::KNumCTA; static constexpr int KPartN = KernelTraits::KBlockN; at::Tensor streamk_ws; @@ -640,10 +632,9 @@ void gemm_impl_body(GemmParams& params, const int sm_count, int smem_size = cutlass::arch::sm100_smem_capacity_bytes; - // Two instantiations, picked by pointer: data-parallel (unchanged codegen, - // used whenever nothing is split) and fused stream-K. The `if constexpr` - // keeps traits without KSupportsStreamK (all but BF16 dense no-bias - // no-alpha) from instantiating a dead stream-K copy. + // Two instantiations picked by pointer: data-parallel and fused + // stream-K; `if constexpr` keeps other traits from instantiating a dead + // stream-K copy. auto* kernel_ptr_dp = &gemm_kernel; void const* kernel_ptr = (void const*)kernel_ptr_dp; @@ -672,8 +663,7 @@ void gemm_impl_body(GemmParams& params, const int sm_count, } if (streamk_active) { - // Reduce tail fp32 partials into D (whole tiles were already stored - // to D by the main launch). + // Reduce tail partials into D; whole tiles were already stored. launch_stream_k_reduce( static_cast(params.ptr_d), streamk_ws.data_ptr(), scheduler_params.streamk_tail_base, scheduler_params.streamk_rem, diff --git a/csrc/kernel/gemm/gemm_tile.cuh b/csrc/kernel/gemm/gemm_tile.cuh index 5bf1b1b..b5bc3b4 100644 --- a/csrc/kernel/gemm/gemm_tile.cuh +++ b/csrc/kernel/gemm/gemm_tile.cuh @@ -26,8 +26,7 @@ namespace halops { inline constexpr int kSwapEpiChunk = 2 * kMatRows; inline constexpr int kSfbRowShiftAlign = 64; -// --------------------------------------------------------------------------- -// Dense GEMM tile parameters; this is the only tile definition in the tree. +// Dense GEMM tile parameters. // // BM, BN, BK KBlockM/N/K; for SwapAB, BM is the weight's M and BN the // activation extent. @@ -46,9 +45,7 @@ inline constexpr int kSfbRowShiftAlign = 64; // NTAIL KForceEpiNPredicate (predicated store on power-of-2 N). // BF16 KIsBF16 (native BF16 GEMM, no scale factors). // ATOM CTAs per MMA atom: 0 = auto (CM*CN > 1 ? 2 : 1), 1 = 1SM, -// 2 = 2x1SM. Decoupled from the cluster shape so a 1SM atom -// can still sit in a multi-CTA cluster and share loads. -// --------------------------------------------------------------------------- +// 2 = 2x1SM. template 0 ? sm_count : GetSmCount(); } diff --git a/csrc/kernel/gemm/kernel_traits.cuh b/csrc/kernel/gemm/kernel_traits.cuh index a495745..a91fa80 100644 --- a/csrc/kernel/gemm/kernel_traits.cuh +++ b/csrc/kernel/gemm/kernel_traits.cuh @@ -87,14 +87,12 @@ struct GemmKernelTraits { static constexpr int KNumCTA = IsPairUmma ? 2 : 1; static constexpr int KClusterM = KernelConfig_::KClusterM; static constexpr int KClusterN = KernelConfig_::KClusterN; - // KNumCTA == 1: single-CTA UMMA (SM100_MMA_..._SS, cta_group::1) - // KNumCTA == 2: pair-UMMA (SM100_MMA_..._2x1SM_SS, cta_group::2) - // FP4: MMA K-increment is 64 elements; FP8: MMA K-increment is 32 elements. - // BF16: non-block-scaled kind::f16 MMA, K-increment is 16 elements. + // KNumCTA 1: cta_group::1 UMMA; 2: pair-UMMA (2x1SM, cta_group::2). + // MMA K step: 64 for FP4, 32 for FP8, 16 for BF16. static constexpr bool KIsFP4 = KernelConfig_::KIsFP4; static constexpr bool KIsBF16 = KernelConfig_::KIsBF16; - // Narrow the A TMA box to the real M below KBlockM (the UMMA - // still reads KBlockM rows and the epilogue drops D past M); + // Narrow the A TMA box to the real M below KBlockM (the UMMA still reads + // KBlockM rows; the epilogue drops D past M). static constexpr bool KNarrowA = NarrowA_ && (KDenseW8A8MXFP8 || (KernelType == KernelMode::Batch && !AddBias)) && @@ -102,16 +100,10 @@ struct GemmKernelTraits { !SwapAB && !IsPairUmma && !KernelConfig_::KIsFP4 && KBlockK == 128; static constexpr bool KUsePdl = UsePdl_; static constexpr int KMmaK = KIsFP4 ? 64 : (KIsBF16 ? 16 : 32); - // Tail-only stream-K eligibility; single source of truth for the - // scheduler's split decision and for emitting the KStreamK=true kernel. - // Only the BF16 dense no-bias no-alpha epilogue can deposit a raw fp32 - // partial (the bias epilogue has no stream-K path; the reduce kernel does - // not apply alpha). Also excluded, each a silent wrong-result otherwise: - // * SwapAB: the tail fold-back math assumes non-swap traversal - // (m=64 n=19584 k=1024 gave 121% rel error; HALOPS_STREAMK=0 - // disables stream-K); - // * N-predicated tiles: the compact per-tile fp32 partial slot would - // leave holes that the reduce kernel sums. + // Tail-only stream-K: only the BF16 dense no-bias no-alpha epilogue can + // deposit an fp32 partial. SwapAB is excluded (the tail fold-back assumes + // non-swap traversal; m=64 n=19584 k=1024 gave 121% rel error), as are + // N-predicated tiles (their partial slot leaves holes the reduce sums). static constexpr bool KSupportsStreamK = KernelType == KernelMode::Dense && KIsBF16 && !AddBias && !HasAlpha && !SwapAB && (KBlockN % 128 == 0 || KBlockN == 32 || KBlockN == 64) && @@ -140,8 +132,8 @@ struct GemmKernelTraits { static constexpr int KQuantAccCols = KAccColsPerOut * mxfp8::kGroup; // Epilogue warp groups split N: 1 for bf16 SwapAB (small N) and for a // quantized tile narrower than two quant groups, 2 otherwise. - // KEpilogueWarpGroupsOverride can force 1, e.g. to make KBlockN=32 legal - // at CtaM==64 (KEpiComputeN = 32 meets the T2R atom floor). + // KEpilogueWarpGroupsOverride forces 1, e.g. to make KBlockN=32 legal at + // CtaM==64 (KEpiComputeN=32 meets the T2R atom floor). static constexpr int KEpilogueWarpGroupCount = KernelConfig_::KEpilogueWarpGroupsOverride != 0 ? KernelConfig_::KEpilogueWarpGroupsOverride @@ -159,10 +151,9 @@ struct GemmKernelTraits { static constexpr int KNumRegsEpilogue = KernelConfig_::KNumRegsEpilogue; static constexpr bool SkipTmemFence = KernelConfig_::SkipTmemFence; static constexpr int KNumRegsOther = 88; - // Whether to do runtime register redistribution (setmaxnreg): needs enough - // warps for the 208+88 split. Not keyed on the epilogue warp-group count; - // without it ptxas gives every warp one flat budget (54-87 regs, starving - // the epilogue). Quantized configs keep the warp-group-count rule. + // setmaxnreg redistribution (208 + 88 split) for BF16 needs enough warps; + // without it ptxas gives every warp one flat budget (54-87 regs), starving + // the epilogue. Quantized configs keep the warp-group-count rule. static constexpr bool KRedistributeRegs = KIsBF16 ? (KNumWarp >= 8 && (!SwapAB || KernelType == KernelMode::Dense)) : KEpilogueWarpGroupCount != 1; @@ -177,20 +168,14 @@ struct GemmKernelTraits { static constexpr int KEpiComputeN = KBlockN / KEpilogueWarpGroupCount; using EpiComputeTile = cute::Shape, cute::Int>; - // Sub-tile for overlap TMEM load splitting. - // When overlap is enabled, always use 16-wide sub-tiles (TMEM load atom - // width). This is fully general: KTmemOverlapCols need not divide - // KEpiComputeN evenly, as long as both are multiples of 16. Falls back to - // EpiComputeTile when overlap is disabled (KTmemOverlapCols==0). + // Overlap TMEM loads use 16-wide sub-tiles (the TMEM load atom width); + // KTmemOverlapCols need not divide KEpiComputeN, only both be multiples of + // 16. Without overlap this is EpiComputeTile. // - // Non-power-of-2 KBlockN (e.g. 96/112/224, for one-wave occupancy): the - // T2R tables only have atoms for KEpiComputeN in {16, 32, 64, 128}, so - // such widths are decomposed into uniform KSubTileN=32 sub-tiles (16 would - // give only 8 fp32/thread, too few for SM100_STORE_256bit). Not legal on - // the 2SM "2x2" layout, whose second N half sits on datapaths 64-127: a - // 32-wide slice straddles the half boundary and writes wrong elements. - // A per-warp-group width of 8 (224-pair, KEpiComputeN=112 falls back to - // 32-wide sub-tiles here) has no single atom either. + // Non-power-of-2 KBlockN (96/112/224) has no T2R atom for KEpiComputeN and + // splits into 32-wide sub-tiles (16 gives only 8 fp32/thread, too few for + // SM100_STORE_256bit). Not legal on the 2SM "2x2" layout: a 32-wide slice + // straddles the N-half boundary and writes wrong elements. static constexpr bool KEpiNIsSingleAtom = (KEpiComputeN == 16 || KEpiComputeN == 32 || KEpiComputeN == 64 || KEpiComputeN == 128); @@ -206,7 +191,6 @@ struct GemmKernelTraits { : (KEpiComputeN % 32 == 0 ? 32 : 16))) : ((KTmemOverlapCols == 0 && KEpiComputeNHasAtom) ? KEpiComputeN : 16); - // KIs2SmHalfM spelled out (it is declared further down). static_assert(!KIsBF16 || KEpiNIsSingleAtom || !(KNumCTA == 2 && KBlockM == 128), "a non-power-of-2 KBlockN cannot use the 2SM 128-row \"2x2\" " @@ -228,12 +212,10 @@ struct GemmKernelTraits { (KTmemOverlapCols == 16 || KTmemOverlapCols == 32 || KTmemOverlapCols == 64 || KTmemOverlapCols == 128); - // ---- TMEM column budget ---------------------------------------------- - // tcgen05.alloc takes a power-of-2 column count in [32, 512]; accumulators - // need KEpilogueStages * KBlockN columns. Right-sizing is perf-neutral but - // gives a truthful footprint for small tiles. BF16 without overlap only: - // block-scaled dtypes also keep SFA/SFB in TMEM, and overlap shares - // columns between stages, so both keep the full 512. + // TMEM budget: tcgen05.alloc takes a power-of-2 column count in [32, 512]; + // accumulators need KEpilogueStages * KBlockN. Only BF16 without overlap + // right-sizes; block-scaled dtypes also hold SFA/SFB in TMEM and overlap + // shares columns between stages. static constexpr int KAccTmemColumns = KEpilogueStages * KBlockN; static constexpr int round_up_tmem_columns(int v) { int r = 32; @@ -247,12 +229,10 @@ struct GemmKernelTraits { ? round_up_tmem_columns(KAccTmemColumns) : 512; - // ---- TMEM load (T2R) atom selection: depends on BOTH per-CTA M and N ---- - // `NNdp` is the number of TMEM datapath lanes an atom addresses. A 1SM - // 64-row accumulator only occupies the first 16 lanes of each of the 4 - // subpartitions, so it needs a 16dp atom (32dp fails "Non-injective - // Layout"), with the N repeat count HALVED relative to 32dp. The tiled - // copy stays 128 threads either way. + // T2R atom selection depends on per-CTA M and N. NNdp is the number of + // datapath lanes an atom addresses: a 1SM 64-row accumulator fills only 16 + // lanes per subpartition, so it needs a 16dp atom (32dp fails + // "Non-injective Layout") with the N repeat halved. Both use 128 threads. static constexpr int KEpiCtaM = KBlockM / KNumCTA; static_assert(KEpiCtaM == 64 || KEpiCtaM == 128, "UMMA accumulators support 64 or 128 rows per CTA only " @@ -264,15 +244,12 @@ struct GemmKernelTraits { "is half the 32dp one; KEpiComputeN < 32 would land on " "16dp32b8x, which cannot fill SM100_STORE_256bit."); - // ---- Which TMEM accumulator layout are we actually reading? ------------ - // 1CTA, KBlockM=64 -> 1SM half-subpartition: 16 lanes/subpartition, N - // in TMEM columns (16dp atom). - // 2CTA, KBlockM=128 -> 2SM "2x2": second half of N on datapaths 64-127, - // only N/2 columns used (32dp atom). - // 2CTA, KBlockM=256 -> 2SM "4x1": all 128 lanes, N in columns. - // The "2x2" case needs a 32dp atom AND an epilogue tile spanning the full - // KBlockN (KEpilogueWarpGroupsOverride = 1); otherwise warps 2/3 address - // outside the tile and the output is silently wrong (no assert fires). + // Accumulator layout being read: + // 1CTA M=64 -> half subpartition, 16 lanes, N in columns (16dp atom); + // 2CTA M=128 -> "2x2", second N half on datapaths 64-127, N/2 columns; + // 2CTA M=256 -> "4x1", all 128 lanes, N in columns. + // "2x2" needs a 32dp atom and a full-KBlockN epilogue tile + // (KEpilogueWarpGroupsOverride=1), else warps 2/3 address outside it. static constexpr bool KIs2SmHalfM = (KNumCTA == 2) && (KEpiCtaM == 64); static constexpr int KEpiTmemDp = (KNumCTA == 1 && KEpiCtaM == 64) ? 16 : 32; @@ -283,9 +260,8 @@ struct GemmKernelTraits { "KEpilogueWarpGroupsOverride = 1) or warps 2/3 address " "outside the tile and the output is silently wrong."); - // CopyOp for loading the full overlap region in one shot (when - // KOverlapSingleLoad). Width-matched to KTmemOverlapCols. Fallback to 16x - // when not single-load. + // CopyOp for the whole overlap region when KOverlapSingleLoad; width + // matched to KTmemOverlapCols, else 16x. using CopyOpT2R_Overlap = cute::conditional_t< KEpiTmemDp == 16, // 16dp: N repeat halved relative to the 32dp column below. @@ -312,10 +288,9 @@ struct GemmKernelTraits { static constexpr int KWideTilesTotal = KBlockN / KOverlapLoadN; - // Select TMEM load op based on EpiComputeTile N dimension (and CtaM). - // The `Nx` suffix is the column count; a mismatched width silently moves - // the wrong columns, so every width a config can ask for needs its own - // arm. The 16dp series (CtaM == 64) uses HALVED atom width (N/2). + // T2R op for EpiComputeTile N (and CtaM). `Nx` is the column count; a + // mismatched width moves the wrong columns, so every reachable width needs + // its own arm. The 16dp series (CtaM=64) uses half-width atoms. using CopyOpT2R = cute::conditional_t< KEpiTmemDp == 16, cute::conditional_t< @@ -325,8 +300,7 @@ struct GemmKernelTraits { cute::SM100_TMEM_LOAD_16dp32b16x>>, cute::conditional_t< KIs2SmHalfM, - // 2SM "2x2": only KEpiComputeN/2 TMEM columns are used, so the - // column repeat is halved relative to the 4x1 case below. + // 2SM "2x2": N/2 columns are used, so the repeat is halved. cute::conditional_t< KEpiComputeN == 128, cute::SM100_TMEM_LOAD_32dp32b64x, cute::conditional_t>>>>>; - // Overlap path: 16-wide sub-tile load (16 fp32/thread fills - // SM100_STORE_256bit; 8x is too few). No overlap: width-matched CopyOpT2R. - // CtaM==64 halves the repeat count, as above. - // - // TMEM columns per KSubTileN-wide sub-tile: N/2 on the 16dp and 2SM "2x2" - // layouts (upper N half on other datapaths), N on 4x1. + // Overlap: 16-wide sub-tile load (16 fp32/thread fills SM100_STORE_256bit; + // 8x is too few). No overlap: width-matched CopyOpT2R. CtaM=64 halves the + // repeat. Columns per sub-tile: N/2 on 16dp and "2x2", N on 4x1. static constexpr int KSubTileTmemCols = (KEpiTmemDp == 16 || KIs2SmHalfM) ? KSubTileN / 2 : KSubTileN; // Width-matched atom for one sub-tile; only for non-power-of-2 KBlockN. @@ -380,10 +351,8 @@ struct GemmKernelTraits { cute::SM100_TMEM_LOAD_16dp32b8x, cute::SM100_TMEM_LOAD_32dp32b16x>>>; - // ---- Close the CopyOpT2R fall-through --------------------------------- - // Each chain above ends in a default (narrowest) atom, which make_tmem_copy - // replicates over the tile. That is only correct when the atom width - // divides the tile; otherwise it compiles clean and writes wrong elements. + // Each chain above ends in the narrowest atom; make_tmem_copy replicates + // it over the tile, which is only correct when the atom width divides it. static_assert(!KIsBF16 || KEpiComputeN % KSubTileN == 0, "the epilogue sub-tile loop must cover KEpiComputeN exactly"); static_assert(!KIsBF16 || KEpiNIsSingleAtom || KTmemOverlapCols != 0 || @@ -393,10 +362,9 @@ struct GemmKernelTraits { "the tile when the tile's TMEM column count is a multiple of " "16. Widen the table before using such a width."); - // Non-power-of-2 KBlockN tiles may overhang N, so the store is predicated - // at KSubTileN granularity (n must be a multiple of it). A config can - // force this for a power-of-2 KBlockN via KForceEpiNPredicate (e.g. - // N=1600 on a 128-wide tile, KSubTileN=64). + // Non-power-of-2 KBlockN may overhang N, so the store is predicated at + // KSubTileN granularity (n must be a multiple of it). KForceEpiNPredicate + // forces this for a power-of-2 KBlockN (N=1600 on a 128-wide tile). static constexpr bool KEpiNeedsNPredicate = KIsBF16 && (((KBlockN & (KBlockN - 1)) != 0) || KernelConfig_::KForceEpiNPredicate); @@ -449,16 +417,11 @@ struct GemmKernelTraits { "Static cluster shape used: TileShape should be " "evenly divided by TiledMma"); - // The F16BF16 atom has NO scale-factor members (SFVecSize, MMA_ScaleFactor, - // FrgTypeSFA/SFB). For BF16 the SF types below are derived from a dummy - // MXF4 MMA so they stay well-formed (never used at runtime; the mainloop - // guards them with if constexpr(!KIsBF16)). MXF4 (SFVecSize=16) rather - // than MXF8F6F4 (32): 64 / 16 = 4 matches the SfAtom's 4-in-K granularity. - // - // The dummy uses a fixed SFTileShape rather than TileShape, so the - // block-scaled constraints (1-CTA M == 128, KBlockK == 64) do not leak - // into BF16 tile choices (e.g. M=64, KBlockK=32). For FP8/FP4 SFTileShape - // IS TileShape and TiledMmaForSF IS TiledMma: codegen unchanged. + // F16BF16 has no SF members, so BF16 derives the SF types below from a + // dummy MXF4 MMA; they are unused at runtime. MXF4 (SFVecSize=16) rather + // than MXF8F6F4 (32): 64/16 = 4 matches the SfAtom's 4-in-K granularity. + // The dummy keeps a fixed SFTileShape so the block-scaled constraints + // (1-CTA M==128, KBlockK==64) do not leak into BF16 tiles. static constexpr int KSFDummyM = KNumCTA == 1 ? 128 : 256; using SFTileShape = cute::conditional_t< KIsBF16, @@ -480,10 +443,9 @@ struct GemmKernelTraits { cute::conditional_t; - // For unaligned-N pair tiles (see IsSfbUnaligned) the SFB tile is a run of - // 128-row atoms, so the SF MMA atom is 128 wide rather than round_up(N). - // BF16 never takes this arm (KIsBF16 -> TiledMmaForSF is the dummy, no - // SFB is loaded) and neither does the aligned-N majority. + // Unaligned-N pair tiles (IsSfbUnaligned) load SFB as a run of 128-row + // atoms, so the SF MMA atom is 128 wide rather than round_up(N). BF16 + // never takes this arm. using MMA_SF_T = cute::conditional_t< KIsBF16 || SwapAB || KBlockN % 128 == 0, typename TiledMmaForSF::MMA_ScaleFactor, @@ -501,8 +463,7 @@ struct GemmKernelTraits { cute::Layout>, cute::Tile>; - // SF fragment types for the mainloop's TMEM SF tensors (from TiledMmaForSF, - // since the BF16 TiledMma lacks them). + // SF fragment types for the mainloop's TMEM SF tensors. using FrgTypeSFA = typename TiledMmaForSF::FrgTypeSFA; using FrgTypeSFB = typename TiledMmaForSF::FrgTypeSFB; @@ -524,10 +485,9 @@ struct GemmKernelTraits { cute::size<1>(CtaShape_MNK{}) < Blk_MN{}; static constexpr int IsCtaN64 = cute::size<1>(CtaShape_MNK{}) == 64; // A pair tile whose N is not a multiple of the 128-row SF atom (e.g. 224) - // starts at a 32-row-aligned offset inside an atom. SFB is then loaded as - // the covering run of whole atoms, and the MMA's SFB TMEM address is moved - // forward by the offset (one TMEM column holds 32 rows of an atom). - // BF16 has no scale factors and never takes this path. + // starts at a 32-row-aligned offset inside an atom; SFB is then the + // covering run of whole atoms and the MMA's SFB address moves forward by + // that offset (one TMEM column holds 32 atom rows). BF16 skips this. static constexpr bool IsSfbUnaligned = !KIsBF16 && !KIsFP4 && (!SwapAB || KernelConfig_::KSwapSfbRun) && KBlockN > 128 && KBlockN % 128 != 0; @@ -597,10 +557,9 @@ struct GemmKernelTraits { using SmemLayoutAtomSFA = decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFA(TiledMmaForSF{}, SFTileShape{})); - // Unaligned-N SFB loads a run of KSfbAtoms whole 128-row atoms (see - // IsSfbUnaligned), so the SMEM atom covers CTA_N_SF rows rather than - // SFTileShape's N. For every other tile (incl. the BF16 dummy, whose SF - // layouts are never used at runtime) the SFTileShape form applies. + // Unaligned-N SFB loads KSfbAtoms whole atoms, so the SMEM atom covers + // CTA_N_SF rows instead of SFTileShape's N. Every other tile uses the + // SFTileShape form. using SmemLayoutAtomSFB = cute::conditional_t< IsSfbUnaligned, decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFB( @@ -705,9 +664,9 @@ struct GemmKernelTraits { typename AccumulatorPipeline::SharedStorage; alignas(16) AccumulatorPipelineStorage accumulator; - // Pair-UMMA overlap: the peer CTA's overlap WG must finish T2R before - // the leader issues the next UMMA; the leader's NamedBarrier cannot see - // it, so the peer arrives on this cluster barrier. + // Pair-UMMA overlap: the peer's overlap WG must finish T2R before the + // leader issues the next UMMA, so it arrives on this cluster barrier + // (the leader's NamedBarrier cannot see it). alignas(8) typename cutlass::arch::ClusterBarrier::ValueType overlap_cluster_bar; diff --git a/csrc/kernel/gemm/mainloop_fwd.cuh b/csrc/kernel/gemm/mainloop_fwd.cuh index 9e82b77..ff1dfaa 100644 --- a/csrc/kernel/gemm/mainloop_fwd.cuh +++ b/csrc/kernel/gemm/mainloop_fwd.cuh @@ -37,8 +37,7 @@ struct CollectiveMainloop { using TileShape = typename KernelTraits::TileShape; using TileShape_SF = typename KernelTraits::TileShape_SF; - // Stand-in tile shape the dummy SF atom accepts (== TileShape for FP8/FP4; - // see kernel_traits.h). + // Stand-in tile shape for the dummy BF16 SF atom; == TileShape for FP8/FP4. using SFTileShape = typename KernelTraits::SFTileShape; using ClusterShape_MNK = typename KernelTraits::ClusterShape_MNK; using EpilogueTile = typename KernelTraits::EpilogueTile; @@ -321,8 +320,7 @@ struct CollectiveMainloop { SmemLayoutB{}(cute::_, cute::_, cute::_, cute::Int<0>{}), TileShape{}, TiledMma{}, cluster_layout_vmnk); - // BF16: SF pointers are null (encoding a TMA atom from them would - // fault on the host), so return default-constructed SF atoms. + // BF16: SF pointers are null, so return default-constructed atoms. if constexpr (KIsBF16) { return {args.layout_A, args.layout_B, @@ -489,9 +487,8 @@ struct CollectiveMainloop { }(); cute::Tensor cta_sA = shared_storage.tensor_sA(); cute::Tensor cta_sB = shared_storage.tensor_sB(); - // Slice by the atom's thread coordinate, not the flat cluster rank: - // with a 1SM atom in a multi-CTA cluster the extra CTAs would index - // past the atom's thread layout and get invalid A/B fragments. + // Slice by the atom's thread coord, not the flat cluster rank: extra + // CTAs of a multi-CTA cluster would index past the atom layout. cute::ThrMMA cta_mma = tiled_mma.get_slice( block_rank_in_cluster % cute::size(typename TiledMma::AtomThrID{})); @@ -587,10 +584,9 @@ struct CollectiveMainloop { block_rank_in_cluster % cute::size(typename TiledMma_SF::AtomThrID{})); - // SF tiling must use SFTileShape + TiledMmaForSF consistently: for BF16 - // they are dummy stand-ins (kernel_traits.h) and mixing them with the - // real ones breaks tma_partition's mode-0 sizes, even though no SF - // load is issued. Identical to the real ones for FP8/FP4. + // SFTileShape and TiledMmaForSF must be used together: for BF16 they + // are dummy stand-ins, and mixing them with the real ones breaks + // tma_partition's mode-0 sizes. cute::ThrMMA cta_mma_sfa = TiledMmaForSF{}.get_slice( block_rank_in_cluster % cute::size(typename TiledMmaForSF::AtomThrID{})); @@ -707,9 +703,8 @@ struct CollectiveMainloop { lo + KernelTraits::KBlockM - narrow_rows); narrow_smem_row = narrow_row - lo; } - // Stream-K: a work item may cover only a K-slice. Producer and - // mma() consumer both take the range from the scheduler, so stage - // counts always match. + // Stream-K: a work item may cover only a K-slice; producer and + // consumer take the range from the scheduler, so stages match. const uint32_t k_lo = scheduler.k_begin(); const uint32_t k_hi = scheduler.k_end(); for (uint32_t k_tile_id = k_lo; k_tile_id < k_hi; ++k_tile_id) { @@ -718,8 +713,7 @@ struct CollectiveMainloop { mainloop_pipe_producer_state); prologue_stage_idx = mainloop_pipe_producer_state.index(); - // Issue A, B (+ SFA, SFB unless BF16) TMA copies on the same - // barrier. + // A, B (+ SFA, SFB unless BF16) TMA copies share one barrier. if (select_thr) { if constexpr (IsSfbRowShift) { cutlass::arch::ClusterTransactionBarrier:: @@ -939,13 +933,9 @@ struct CollectiveMainloop { AccumulatorPipelineState accumulator_pipe_producer_state = cutlass::make_producer_start_state(); - // KStreamK=false only: the next tile's accumulator stage and first - // k-stage are waited on right after the current tile's MMAs are - // issued, before the TMEM overlap barrier, hiding the producer's - // stage latency. With stream-K the K ranges of consecutive work - // items differ, so the first k-stage of the next item is not the - // next pipeline stage -- the prefetch is skipped and every k-tile - // waits explicitly. + // KStreamK=false only: prefetch the next tile's accumulator stage and + // first k-stage right after the MMAs are issued, hiding producer + // latency. With stream-K the K ranges differ, so every k-tile waits. [[maybe_unused]] bool next_tile_ready = false; while (scheduler.is_valid()) { @@ -994,8 +984,8 @@ struct CollectiveMainloop { const uint32_t k_hi = scheduler.k_end(); for (uint32_t k_tile_id = k_lo; k_tile_id < k_hi; ++k_tile_id) { prologue_stage_idx = mainloop_pipe_consumer_state.index(); - // Data-parallel: the first k-stage of a prefetched tile was - // already waited on below (after the previous tile's MMAs). + // Data-parallel: the prefetched first k-stage was already + // waited on. if constexpr (KStreamK) { mainloop_pipeline.consumer_wait( mainloop_pipe_consumer_state); @@ -1024,8 +1014,8 @@ struct CollectiveMainloop { for (uint32_t k_block_id = 0; k_block_id < iter_k; ++k_block_id) { if constexpr (KIsBF16) { - // kind::f16 MMA: no scale factors; accumulate flag - // comes from tiled_mma.accumulate_. + // kind::f16 MMA: no scale factors, only the + // accumulate flag. gemm(tiled_mma, tile_rA(cute::_, cute::_, k_block_id, prologue_stage_idx), @@ -1061,9 +1051,8 @@ struct CollectiveMainloop { scheduler.advance(); if constexpr (!KStreamK) { - // Prefetch: acquire the next tile's accumulator stage and - // wait on its first mainloop stage now, so the next - // iteration's MMA issue path starts with data ready. + // Prefetch: acquire the next accumulator stage and wait on + // its first k-stage now. next_tile_ready = scheduler.is_valid(); if (next_tile_ready) { accumulator_pipeline.producer_acquire( diff --git a/csrc/kernel/gemm/stream_k_reduce.cuh b/csrc/kernel/gemm/stream_k_reduce.cuh index d14ead0..25da308 100644 --- a/csrc/kernel/gemm/stream_k_reduce.cuh +++ b/csrc/kernel/gemm/stream_k_reduce.cuh @@ -18,18 +18,13 @@ #include -// Reduction pass for tail-only stream-K (see tile_scheduler.h). +// Reduction pass for tail-only stream-K (see tile_scheduler.cuh). // -// The first `tail_base` cluster-tiles are data-parallel and written straight -// to D. Each of the remaining `rem` tiles is split into `splits` K-chunks, each -// writing a raw fp32 partial to its own workspace slot: -// -// partial[ ((t * splits + s) * num_cta + v) ][ cta_m ][ block_n ] -// -// (v = CTA index inside the cluster). This kernel sums the `splits` partials of -// each tail tile and casts to TypeD in place in D; cost scales with -// rem*splits only. A shared fp32 buffer with atomicAdd is slower (address -// contention serializes the epilogue stores). +// The first `tail_base` cluster-tiles are written straight to D; the remaining +// `rem` tiles are split into `splits` K-chunks, each depositing an fp32 partial +// to partial[((t * splits + s) * num_cta + v)][cta_m][block_n]. This kernel +// sums the per-tile partials into D. Cost scales with rem*splits only; a shared +// buffer with atomicAdd serializes on the address. template __global__ void stream_k_reduce_kernel(TypeD* __restrict__ ptr_d, float const* __restrict__ ptr_partial, @@ -41,9 +36,9 @@ __global__ void stream_k_reduce_kernel(TypeD* __restrict__ ptr_d, return; } - // Unflatten: [t][v][cta_m][block_n], 4 columns per thread (scalar is - // issue-bound). BlockN % 4 == 0 and slots are CtaM*BlockN floats, so the - // float4 loads and 4x TypeD store are naturally aligned. + // Unflatten: [t][v][cta_m][block_n], 4 columns per thread (scalar stores + // are issue-bound). Slots are CtaM*BlockN floats, so float4 loads and the + // 4x TypeD store stay aligned. constexpr int kVec = 4; constexpr int kColVecs = BlockN / kVec; const int col = static_cast(idx % kColVecs) * kVec; @@ -53,7 +48,6 @@ __global__ void stream_k_reduce_kernel(TypeD* __restrict__ ptr_d, const int v = static_cast(rest % NumCta); const int t = static_cast(rest / NumCta); - // Sum the `splits` partials of these elements. float4 acc = make_float4(0.f, 0.f, 0.f, 0.f); const int64_t slot_stride = static_cast(CtaM) * BlockN; const int64_t within = static_cast(row) * BlockN + col; @@ -68,8 +62,7 @@ __global__ void stream_k_reduce_kernel(TypeD* __restrict__ ptr_d, acc.w += p.w; } - // Map the tail work id to cluster coords as the scheduler's linear path - // does. + // Map the tail work id to cluster coords (scheduler's linear path). const int base_tile = tail_base + t; int cluster_m, cluster_n; if (m_fast) { diff --git a/csrc/kernel/gemm/tile_scheduler.cuh b/csrc/kernel/gemm/tile_scheduler.cuh index b44148a..375ab37 100644 --- a/csrc/kernel/gemm/tile_scheduler.cuh +++ b/csrc/kernel/gemm/tile_scheduler.cuh @@ -57,16 +57,11 @@ struct TileScheduler { static constexpr int kExpertClusterRows = kExpertTileSize * kExpertClusterTiles; - // --- Preamble-cost specializations --- - // The constructor runs in every warp of the CTA and is pure per-CTA - // preamble; these constants let the compiler drop provably dead parts. - // - // kAlwaysCompact: host sets use_compact_sched = (S == 1), and S > 1 only - // with UseTileSwizzle, so without swizzle only the compact path is - // reachable (tile_num_m_/tile_num_n_ are then dead too). + // Preamble specializations: the constructor runs in every warp and is + // pure per-CTA preamble. Without swizzle only the compact path is + // reachable (S > 1 implies UseTileSwizzle). static constexpr bool kAlwaysCompact = !UseTileSwizzle; - // kIsSingleCtaCluster: cluster == CTA, so cluster queries reduce to - // gridDim/blockIdx (cheaper than CuTe's %%nclusterid/%%clusterid reads). + // cluster == CTA: use gridDim/blockIdx directly. static constexpr bool kIsSingleCtaCluster = (KernelTraits::KNumCTA == 1) && (cute::size(ClusterShape_MNK{}) == 1); @@ -81,16 +76,14 @@ struct TileScheduler { int expert_ctm; // per-expert cluster-tiles in M int expert_ctn; // per-expert cluster-tiles in N int total_tiles; // num_logical_experts * tiles_per_expert - // Host-precomputed fast divmod (avoid runtime integer division) - cutlass::FastDivmod divmod_tiles; // ÷ tiles_per_expert - cutlass::FastDivmod divmod_ss; // ÷ S*S - cutlass::FastDivmod - divmod_blocks; // ÷ blocks_fast (mode-dependent, see below) - cutlass::FastDivmod divmod_s; // ÷ S - - // Compact scheduling flag (set by host, all other compact state - // computed on device — no D2H sync needed). - bool use_compact_sched; // true for Masked mode with linear path (S=1) + // Host-precomputed fast divmod (avoid runtime division). + cutlass::FastDivmod divmod_tiles; // ÷ tiles_per_expert + cutlass::FastDivmod divmod_ss; // ÷ S*S + cutlass::FastDivmod divmod_blocks; // ÷ blocks_fast + cutlass::FastDivmod divmod_s; // ÷ S + + // Compact scheduling flag; the rest of the state is derived on device. + bool use_compact_sched; // true for Masked with the linear path (S=1) int batch_own_tiles; cutlass::FastDivmod divmod_batch_period; cutlass::FastDivmod divmod_slow_tiles; @@ -104,22 +97,19 @@ struct TileScheduler { // true → M-fast (tile_id ÷ expert_ctm): consecutive tiles sweep M. bool traverse_m_fast; - // Contiguous-range tile assignment instead of strided (Batch SwapAB - // only). See to_underlying_arguments. + // Contiguous-range tile assignment instead of strided (Batch SwapAB). bool chunked_assign; - // --- Tail-only stream-K (Naive only; streamk_rem == 0 disables) --- - // C clusters over W tiles: the first streamk_tail_base = (W/C)*C tiles - // stay data-parallel (full K); each of the remaining streamk_rem tiles - // is split into streamk_splits K-chunks on different clusters, so the - // makespan drops from ceil(W/C) to W/C + 1/splits tile-times and only - // the tail needs fp32 partials. Fused work-id space, one launch: - // [0, tail_base) whole tiles, full K range - // [tail_base, tail_base + rem * splits) (tail tile, K-chunk) pairs + // Tail-only stream-K (streamk_rem == 0 disables). Over C clusters and + // W tiles, the first (W/C)*C tiles stay data-parallel; each remaining + // tile is split into streamk_splits K-chunks, so the makespan drops + // from ceil(W/C) to W/C + 1/splits and only the tail needs fp32 + // partials. Work-id space: [0, tail_base) whole tiles, then + // (tail tile, K-chunk) pairs. int streamk_tail_base; int streamk_rem; int streamk_splits; - int k_tiles; // ceil_div(k, KBlockK); chunk bounds are derived from it + int k_tiles; // ceil_div(k, KBlockK) }; static Params to_underlying_arguments(int m, int n, int num_experts = 0, @@ -183,13 +173,10 @@ struct TileScheduler { int tiles_per_expert = blocks_m * blocks_n * S * S; int total_tiles = num_logical_experts * tiles_per_expert; - // --- Linear-path traversal orientation (Naive only) --- - // The operand indexed by the fast dimension stays L2-resident; the - // other is streamed once. Keep the smaller one resident: - // N-fast → B (N×K) resident; right when N <= M. - // M-fast → A (M×K) resident; right when M < N. - // Naive non-SwapAB uses M-fast when m < n (N-fast re-reads a large B - // from DRAM every wave). HALOPS_TRAVERSE_MFAST=0 forces N-fast. + // The operand indexed by the fast dimension stays L2-resident, so + // keep the smaller one: N-fast for N <= M, M-fast for M < N. Naive + // non-SwapAB picks M-fast when m < n (N-fast re-reads a large B every + // wave). HALOPS_TRAVERSE_MFAST=0 forces N-fast. bool traverse_m_fast = false; if constexpr (KernelTraits::KernelType == KernelMode::Dense && !SwapAB) { @@ -211,27 +198,24 @@ struct TileScheduler { cutlass::FastDivmod divmod_blocks(divmod_blocks_divisor); cutlass::FastDivmod divmod_s(S); - // --- Tail-only stream-K decomposition (Naive only; see Params) --- - // splits must divide k_tiles so every chunk has the same length. + // Tail-only stream-K (see Params). splits must divide k_tiles. int streamk_tail_base = total_tiles; int streamk_rem = 0; int streamk_splits = 1; - // KSupportsStreamK (kernel_traits.h) limits this to BF16 dense without - // bias/alpha (they cannot deposit a partial) and without SwapAB. + // KSupportsStreamK limits this to BF16 dense without bias/alpha or + // SwapAB. if constexpr (KernelTraits::KSupportsStreamK) { - // Default ON; rejected shapes keep streamk_rem == 0 and run the - // plain data-parallel path (no workspace, no reduce launch). - // HALOPS_STREAMK=0 forces the data-parallel path. + // Default on; rejected shapes keep streamk_rem == 0 (no + // workspace, no reduce launch). HALOPS_STREAMK=0 forces off. static const bool streamk_enabled = [] { const char* e = std::getenv("HALOPS_STREAMK"); return e == nullptr || e[0] != '0'; }(); const int C = num_clusters; - // Grid-underfill extension: total_tiles > 0 (not > C) also admits - // whole == 0 (thin M, total_tiles < C), where every tile is split - // so the existing tiles occupy more SMs. p_cap = C / rem keeps - // near-full grids at p = 1 and bounds the workspace at <= C slots. - // HALOPS_STREAMK_FILL=0 restores the tail-only gate. + // Underfill extension: total_tiles > 0 also admits whole == 0 + // (thin M), where every tile is split to occupy more SMs. p_cap + // keeps near-full grids at p = 1 and bounds the workspace at C + // slots. HALOPS_STREAMK_FILL=0 restores the tail-only gate. static const bool streamk_fill = [] { const char* e = std::getenv("HALOPS_STREAMK_FILL"); return e == nullptr || e[0] != '0'; @@ -241,14 +225,14 @@ struct TileScheduler { if (streamk_enabled && S == 1 && C > 0 && k_tiles > 0 && size_ok) { const int whole = total_tiles / C; const int rem = total_tiles - whole * C; - // Split only when the remainder idles >= 5% of total SM-time - // (break-even for the rem*splits partial-tile reduction). + // Split only when the remainder idles >= 5% of SM-time + // (break-even for the partial-tile reduction). const bool worth_it = rem > 0 && (C - rem) * 20 >= (whole + 1) * C; if (worth_it) { - // Use the largest p <= min(C / rem, 8) dividing k_tiles: - // the overhead is fixed, not per-split. - // HALOPS_STREAMK_P=

overrides the cap. + // Largest p <= min(C / rem, 8) dividing k_tiles; the + // overhead is fixed, not per split. HALOPS_STREAMK_P + // overrides the cap. int p_cap = C / rem < 8 ? C / rem : 8; static const int p_forced = [] { const char* e = std::getenv("HALOPS_STREAMK_P"); @@ -265,24 +249,20 @@ struct TileScheduler { } } if (p >= 2 && (whole > 0 || p >= 4)) { - // Underfill gate: with whole == 0, only p >= 4 repays - // the fp32 workspace round-trip and reduce launch. + // With whole == 0 only p >= 4 repays the fp32 + // workspace round-trip and reduce launch. streamk_tail_base = whole * C; streamk_rem = rem; streamk_splits = p; - // Tail items become the (whole+1)-th item of clusters - // 0..rem*p-1, reusing the resident mainloop pipeline. total_tiles = streamk_tail_base + rem * p; } } } } - // Compact scheduling: enabled for Masked and Contiguous modes with S=1 - // (linear path). All compact scheduling state (total_valid_tiles, - // expert cache) is computed on the device — no D2H copy or host-side - // masked_m access. + // Compact scheduling for Masked/Contiguous with S=1; all state is + // computed on device (no D2H copy, no host masked_m access). bool use_compact_sched = false; if (S == 1) { use_compact_sched = true; @@ -314,13 +294,11 @@ struct TileScheduler { kExpertClusterRows) : 0.f; - // --- Contiguous-range assignment (Batch SwapAB only) --- - // SwapAB numbering keeps one item's N segments consecutive, but the - // persistent stride spreads them over different CTAs, so the shared - // activation's L2 reuse becomes a race. Chunked assignment gives CTA i - // the range [i*chunk, (i+1)*chunk), so one CTA processes them - // back-to-back. Only when expert_ctm > 1 (otherwise nothing is - // shared). HALOPS_BATCH_CHUNK=0 restores the stride. + // Chunked assignment (Batch SwapAB): SwapAB numbering keeps one + // item's N segments consecutive, but the persistent stride spreads + // them across CTAs, so the shared activation's L2 reuse becomes a + // race. Give CTA i the range [i*chunk, (i+1)*chunk). Only when + // expert_ctm > 1. HALOPS_BATCH_CHUNK=0 restores the stride. bool chunked_assign = false; if constexpr (KernelTraits::KernelType == KernelMode::Batch && SwapAB && KernelTraits::KIsBF16) { @@ -370,9 +348,8 @@ struct TileScheduler { uint32_t cluster_num_; // stride = number of clusters uint32_t current_tile_id_; // current position in global tile space - // Chunked assignment (Batch SwapAB): step is 1 and each CTA iterates a - // contiguous range ending at tile_end_. Otherwise step = cluster_num_ and - // the range ends at the total tile count. + // Chunked assignment: step 1, range ends at tile_end_; otherwise step is + // cluster_num_ and the range ends at the total tile count. uint32_t advance_step_; uint32_t tile_end_; @@ -405,10 +382,10 @@ struct TileScheduler { uint32_t streamk_rem_; uint32_t streamk_splits_; uint32_t k_tiles_; - // Resolved for the current work item by find_next_valid_tile(). + // Set per work item by find_next_valid_tile(). uint32_t k_begin_; uint32_t k_end_; - int partial_slot_; // -1 = write straight to D; else index into the fp32 ws + int partial_slot_; // -1 writes straight to D, else an fp32 ws slot uint32_t total_valid_tiles_; // sum of valid cluster-tiles across all experts // tile ids only grow, so the expert cache is advanced by forward scan. @@ -497,8 +474,7 @@ struct TileScheduler { streamk_rem_(params.streamk_rem), streamk_splits_(params.streamk_splits), k_tiles_(params.k_tiles) { - // tile_num_m_/tile_num_n_ only feed the non-compact bounds check, so - // skip the two ceil_div's when that path is statically unreachable. + // Only the non-compact bounds check reads these. if constexpr (!kAlwaysCompact) { tile_num_m_ = ceil_div(params.m, size<0>(TileShape{})); tile_num_n_ = ceil_div(params.n, size<1>(TileShape{})); @@ -506,8 +482,7 @@ struct TileScheduler { int cluster_idx; if constexpr (kIsSingleCtaCluster) { - // cluster == CTA: read gridDim/blockIdx directly (cheaper than - // CuTe's %%nclusterid / %%clusterid reads). + // cluster == CTA: use gridDim/blockIdx directly. cluster_num_ = gridDim.x * gridDim.y; cluster_idx = blockIdx.x * gridDim.y + blockIdx.y; // Single-CTA cluster: block_rank 0, flat coord (0,0,0). @@ -537,7 +512,6 @@ struct TileScheduler { cta_v_ = get<0>(cta_coord_vmnk); } - // Compute compact scheduling state on device if (kAlwaysCompact || use_compact_sched_) { if constexpr (IsBatch) { total_valid_tiles_ = batch_valid_tiles_; @@ -552,9 +526,8 @@ struct TileScheduler { total_valid_tiles_ = total_tiles_; cached_expert_ = 0; cached_expert_start_ = 0; - // Single logical expert: the expert-cache fast path must - // always hit (the slow path dereferences masked_m, nullptr - // here), including for folded stream-K base tile ids. + // Single expert: the cache fast path must always hit (the + // slow path dereferences masked_m, which is nullptr here). cached_expert_end_ = 0xFFFFFFFFu; } else { total_valid_tiles_ = 0; @@ -577,11 +550,9 @@ struct TileScheduler { k_end_ = k_tiles_; partial_slot_ = -1; - // Start at this cluster's first tile current_tile_id_ = cluster_idx; advance_step_ = cluster_num_; - // Strided default; stream-K tail work ids lie inside - // total_valid_tiles_ by construction. + // Strided default; stream-K tail ids lie inside total_valid_tiles_. tile_end_ = total_valid_tiles_; if (chunked_assign_) { // Range [cluster_idx*chunk, +chunk), clamped to the tile count. @@ -610,12 +581,10 @@ struct TileScheduler { CUTLASS_DEVICE uint32_t max_m_per_expert() const { return max_m_per_expert_; } - // K-tile range of the current work item. Producer and consumer MUST use - // the same bounds or the mainloop pipeline deadlocks. + // K-tile range of this work item; producer and consumer must agree. CUTLASS_DEVICE uint32_t k_begin() const { return k_begin_; } CUTLASS_DEVICE uint32_t k_end() const { return k_end_; } - // >= 0 when this work item computed only a K-slice and must deposit an - // fp32 partial instead of the final bf16 result. + // >= 0 when this item computed only a K-slice and deposits an fp32 partial. CUTLASS_DEVICE int partial_slot() const { return partial_slot_; } CUTLASS_DEVICE void advance() { @@ -761,11 +730,10 @@ struct TileScheduler { // Scan forward from current_tile_id_ to find the next valid tile, // caching its coordinates in m_idx_/n_idx_/expert_idx_/is_valid_. CUTLASS_DEVICE void find_next_valid_tile() { - // W8A8-dense fast path (quantized only): every tile is valid, so a - // plain divmod resolves the tile without the compact-scan bookkeeping. - // Guarded to !KIsBF16 (BF16 needs the stream-K fold and M-fast - // traversal handled in the compact path below) and !traverse_m_fast_ - // (the divmod orientation below assumes N-fast). + // Quantized dense fast path: every tile is valid, so a plain divmod + // resolves it without the compact scan. Guarded to !KIsBF16 (BF16 + // needs the stream-K fold and M-fast path) and !traverse_m_fast_ + // (the divmod below assumes N-fast). if constexpr (KDenseW8A8MXFP8 && !UseTileSwizzle && !KernelTraits::KIsBF16) { if (!traverse_m_fast_) { @@ -789,17 +757,15 @@ struct TileScheduler { } } if (kAlwaysCompact || use_compact_sched_) { - // Compact path: the tile space only contains valid cluster-tiles, - // so we skip directly to the current tile without iterating through - // large swaths of padding. Only need a lightweight per-CTA check - // for the edge case where the last cluster row of an expert has - // some CTAs with tiles beyond masked_m. With chunked_assign_ the - // per-CTA range ends at tile_end_ instead of total_valid_tiles_. + // The tile space only holds valid cluster-tiles, so jump straight + // to the current one; a per-CTA check covers the last expert row + // whose CTAs run past masked_m. Chunked assignment ends at + // tile_end_. while (current_tile_id_ < tile_end_) { uint32_t cluster_m, cluster_n, expert; - // Stream-K: ids >= streamk_tail_base_ are (tail tile, K-chunk) - // pairs. Fold to the base tile id and resolve the K range and - // partial slot here so all roles see identical values. + // Stream-K: ids past streamk_tail_base_ are (tail tile, + // K-chunk) pairs; resolve base tile, K range and slot once so + // all roles agree. uint32_t base_tile_id = current_tile_id_; k_begin_ = 0; k_end_ = k_tiles_; diff --git a/csrc/kernel/gemm/utils.cuh b/csrc/kernel/gemm/utils.cuh index d9e7cde..1e95175 100644 --- a/csrc/kernel/gemm/utils.cuh +++ b/csrc/kernel/gemm/utils.cuh @@ -73,16 +73,14 @@ struct GemmKernelConfig { static constexpr bool SkipTmemFence = false; static constexpr EpilogueOp KEpiOp = EpilogueOp::Identity; static constexpr bool KSwapSfbRun = false; - // Number of epilogue warp groups; 0 = auto (SwapAB ? 1 : 2). - // KEpiComputeN = KBlockN / count must be >= 32 when CtaM == 64, so narrow - // tiles (e.g. 64x32) need 1. Also drops the inter-warp-group barrier. + // Epilogue warp groups; 0 = auto (SwapAB ? 1 : 2). KEpiComputeN must be + // >= 32 when CtaM == 64, so narrow tiles (e.g. 64x32) need 1. static constexpr int KEpilogueWarpGroupsOverride = 0; - // Force KEpiNeedsNPredicate even for power-of-two KBlockN, so a wide tile - // can serve N % KBlockN != 0 (e.g. N=1600 on a 128-wide tile). + // Force N predication even for power-of-two KBlockN (e.g. N=1600 on a + // 128-wide tile). static constexpr bool KForceEpiNPredicate = false; }; -// BF16 tile definitions live in gemm_tile.cuh alongside the W8A8/W4A4 ones. static constexpr int get_num_warps(int load_c_warp_id, bool add_bias) { int last_warp = add_bias ? load_c_warp_id : (load_c_warp_id - 1); return ((last_warp + 4) / 4) * 4; diff --git a/tests/test_gemm_bf16.py b/tests/test_gemm_bf16.py index 53dc6b1..2d2dc99 100644 --- a/tests/test_gemm_bf16.py +++ b/tests/test_gemm_bf16.py @@ -63,26 +63,19 @@ def test_bf16_gemm_large_m(): def test_bf16_gemm_large_m_n1600(): - # Real production shape (MLA/DSA q_a_proj, bulk prefill): 1600 % 128 == 64, - # so it fits neither the 256- nor the 128-wide full-tile large-M rung. - # Covers 256x128x64_2CTA_Ntail end to end (predicated store at - # KSubTileN=64 granularity, N % 64 == 0 launch check). + # 1600 % 128 == 64: exercises the 256x128 predicated-tail tile end to end. _run_bf16_gemm_case(4096, 1600, 4096) def test_bf16_gemm_large_m_n1600_ladder(): - # N=1600 tail (128-wide MMA, predicated store) across all production M - # values in benchmark/configs/gemm/dense_bf16.yaml. M=1024/2048 are - # mid-M and unaffected by the large-M Ntail change; included here to pin - # the N=1600 correctness baseline across every M rung in one place. + # N=1600 across every M rung of benchmark/configs/gemm/dense_bf16.yaml. for m in (1024, 2048, 4096, 8192, 16384): _run_bf16_gemm_case(m, 1600, 4096) def test_bf16_gemm_large_m_n128(): - # Real production shape (DSA indexer proj): n=128 leaves the KBlockM=256 - # family under half a wave (32 / 64 CTAs of 152), so large-M steps M down - # instead of N -- covers the 64x64 and 64x128 rungs. + # n=128: the 256-wide family underfills a wave, so large-M steps M down + # (64x64 / 64x128 rungs). _run_bf16_gemm_case(4096, 128, 4096) _run_bf16_gemm_case(8192, 128, 4096) @@ -93,8 +86,7 @@ def test_bf16_gemm_mid_m(): def test_bf16_gemm_small_m(): # m < 128 -> 128x64x64 SwapAB small-M path. - # SwapAB maps weight(N-dim) to tile_M=128 (N % 128) and activation(M-dim) - # to tile_N=64 (M % 64), so use n=256 (multiple of 128) and m=64. + # SwapAB: weight is the 128-wide MMA M, the activation the 64-wide N. _run_bf16_gemm_case(64, 256, 256) diff --git a/tests/test_gemm_bf16_grouped.py b/tests/test_gemm_bf16_grouped.py index 25c7492..b27c97e 100644 --- a/tests/test_gemm_bf16_grouped.py +++ b/tests/test_gemm_bf16_grouped.py @@ -14,11 +14,10 @@ # limitations under the License. """ -# Native BF16 (mode="bf16") accuracy tests for the batch / grouped-masked / -# grouped-contiguous GEMM entry points. These share the self-developed -# CollectiveMainloop path with W8A8/W4A4 but take the compile-time KIsBF16 -# branch (no scale factors, no alpha). Golden reference is a plain fp32 matmul -# rounded to bf16, so tolerances are much tighter than the quantized paths. +# Native BF16 accuracy tests for the batch / grouped entry points. They take +# the KIsBF16 branch (no scale factors, no alpha) of the shared mainloop. The +# golden reference is an fp32 matmul rounded to bf16, so tolerances are tighter +# than for the quantized paths. import numpy as np import torch @@ -29,9 +28,9 @@ torch.cuda.manual_seed_all(2026) torch.set_default_device("cuda") -# bf16 output is rounded once by the kernel and once by the reference; a couple -# of ulps of slack is enough. This is far tighter than fp8 (atol 2e-3 rtol 2e-2) -# in relative terms because there is no dequantization error. +# Output is rounded once by the kernel and once by the reference; a couple of +# ulps suffice. There is no dequantization error, so this is far tighter than +# fp8 in relative terms. RTOL = 1e-2 ATOL = 1e-2 From 72166bba8e4d9c0a865339e45039664e47b8c83e Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Tue, 10 Nov 2026 15:30:56 +0800 Subject: [PATCH 05/14] feat(gemm): accept a batch-major [B, M, N] output for bf16 batch GEMM main #29 moved the batch D layout to [M, B * N] so the batched epilogue can share the dense one and feed the fused epilogue ops. That costs 9-11% on large-B / narrow-N / short-K shapes, where the kernel is write-bound and consecutive D rows sit B * N apart (4-8 MiB) instead of N. Keep the default layout and additionally accept the contiguous batch-major [B, M, N] output in mode="bf16" (the layout large-B callers want). Only d_ld and the per-batch row shift differ, both host-side parameters, so no extra kernel instantiation and no change to the default path. Quantized modes keep the 2D-only contract and its error messages. Measured (3 interleaved rounds, medians): restoring the contiguous layout recovers the whole gap -- [8192,64,512,64] 210.9 -> 185.6 us and [8192,64,256,64] 108.0 -> 99.1 us, while control shapes do not move. Also refreshes the two batch_bf16 CI baseline entries that the default layout affects, measured on the current machine (other seven entries and every dense_bf16 entry stay within the 5% threshold and are untouched). Co-Authored-By: Claude Code --- ci/baselines/gemm/batch_bf16.json | 4 ++-- csrc/kernel/gemm/batch_gemm.cu | 26 +++++++++++++++++++++++--- csrc/kernel/gemm/epilogue.cuh | 15 ++++++++++++--- csrc/kernel/gemm/gemm_kernel.cuh | 2 +- csrc/kernel/gemm/kernel_traits.cuh | 2 ++ halops/gemm/batch_gemm.py | 3 +++ tests/test_gemm_bf16_grouped.py | 25 +++++++++++++++++++++++++ 7 files changed, 68 insertions(+), 9 deletions(-) diff --git a/ci/baselines/gemm/batch_bf16.json b/ci/baselines/gemm/batch_bf16.json index 40216c4..d7345b7 100644 --- a/ci/baselines/gemm/batch_bf16.json +++ b/ci/baselines/gemm/batch_bf16.json @@ -57,7 +57,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 192.414 + "median_us": 214.245 }, { "key": { @@ -71,7 +71,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 100.035 + "median_us": 107.999 }, { "key": { diff --git a/csrc/kernel/gemm/batch_gemm.cu b/csrc/kernel/gemm/batch_gemm.cu index 3553f2e..c02be29 100644 --- a/csrc/kernel/gemm/batch_gemm.cu +++ b/csrc/kernel/gemm/batch_gemm.cu @@ -38,7 +38,9 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, "input must be a 3D tensor of shape [B, M, K]"); TORCH_CHECK(weight.dim() == 3, "weight must be a 3D tensor of shape [B, N, K]"); - TORCH_CHECK(output.dim() == 2, + // mode="bf16" also takes the batch-major [B, M, N]; every other mode keeps + // the 2D contract the quantized store assumes. + TORCH_CHECK(output.dim() == 2 || (output.dim() == 3 && mode == "bf16"), "output must be a 2D tensor of shape [M, B * N]"); const int batches = input.size(0); @@ -47,8 +49,25 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, TORCH_CHECK(weight.size(0) == batches, "weight batch dim must match input batch dim, got ", weight.size(0)); - TORCH_CHECK(output.size(0) == m && output.size(1) == int64_t(batches) * n, - "output shape must be [M, B * N]"); + // Native BF16 also accepts the batch-major [B, M, N] output: contiguous + // per item, which writes faster at large B. Every other mode keeps the + // default [M, B * N] (the quantized store's TMA descriptor assumes it). + const bool bmn_out = output.dim() == 3; + if (bmn_out) { + TORCH_CHECK(output.is_contiguous(), + "the [B, M, N] output must be contiguous"); + TORCH_CHECK(output.size(0) == batches && output.size(1) == m && + output.size(2) == n, + "output shape must be [B, M, N], got [", output.size(0), + ", ", output.size(1), ", ", output.size(2), "], expected [", + batches, ", ", m, ", ", n, "]"); + } else { + TORCH_CHECK( + output.size(0) == m && output.size(1) == int64_t(batches) * n, + "output shape must be [M, B * N], got [", output.size(0), ", ", + output.size(1), "], expected [", m, ", ", int64_t(batches) * n, + "]"); + } TORCH_CHECK( !output_sf.has_value() || n % (mxfp8::kGroup * mxfp8::kAtomCols) == 0, "quantized output needs N % 128 == 0, got ", n); @@ -67,6 +86,7 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.num_experts = batches; params.max_m_per_expert = m; params.use_pdl = use_pdl; + params.batch_out_bmn = bmn_out; if (mode == "bf16") { // Native BF16: sfa/sfb/bias/alpha are ignored; dispatch and launch diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index 868577b..b46efcb 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -97,6 +97,8 @@ class CollectiveEpilogue { int rows_per_batch = 0; SituCoef situ{}; int64_t gate_ld = 0; + // Batch D layout: false = [M, B * N] (default), true = [B, M, N]. + bool batch_out_bmn = false; // Stream-K fp32 partial workspace: [slot][CtaShape_M][KBlockN]; null // when stream-K is off. TypeAccumulate* ptr_partial = nullptr; @@ -116,6 +118,7 @@ class CollectiveEpilogue { TypeC const* ptr_c = nullptr; int64_t d_ld; int64_t gate_ld; + bool batch_out_bmn = false; TypeAccumulate* ptr_partial = nullptr; }; @@ -138,7 +141,10 @@ class CollectiveEpilogue { const bool batch = KernelTraits::KernelType == KernelMode::Batch; const int64_t q_n = n / KAccColsPerOut; const int64_t rows = batch ? args.rows_per_batch : m; - const int64_t d_ld = batch ? num_experts * q_n : q_n; + // Batch rows are B * N apart in the default layout, N when the caller + // asked for [B, M, N]. + const int64_t d_ld = + batch ? (args.batch_out_bmn ? q_n : num_experts * q_n) : q_n; cute::TmaDescriptor d_desc{}; if constexpr (KQuantD && !SwapAB) { EncodeTmaDesc<3>( @@ -164,6 +170,7 @@ class CollectiveEpilogue { args.ptr_c, d_ld, args.gate_ld, + args.batch_out_bmn, args.ptr_partial}; } @@ -878,10 +885,12 @@ class CollectiveEpilogue { (static_cast(partial_slot) * KNumCTA + cta_v) * KPartialM * KPartialN; } - // Batch: move the stacked row b * M + r to row r, columns b * N. + // Batch: move the stacked row b * M + r to row r, columns b * N + // (already contiguous in the [B, M, N] layout). int64_t row_shift = 0; if constexpr (KernelTraits::KernelType == KernelMode::Batch) { - const int64_t b = scheduler.expert_idx(); + const int64_t b = + epilogue_params.batch_out_bmn ? 0 : scheduler.expert_idx(); row_shift = b * static_cast(out_n) - b * scheduler.max_m_per_expert() * d_ld; } diff --git a/csrc/kernel/gemm/gemm_kernel.cuh b/csrc/kernel/gemm/gemm_kernel.cuh index f5f9db6..77df8a7 100644 --- a/csrc/kernel/gemm/gemm_kernel.cuh +++ b/csrc/kernel/gemm/gemm_kernel.cuh @@ -618,7 +618,7 @@ void gemm_impl_body(GemmParams& params, const int sm_count, KernelTraits::KernelType == KernelMode::Batch ? params.max_m_per_expert : params.m, - params.situ, params.gate_ld, + params.situ, params.gate_ld, params.batch_out_bmn, streamk_active ? streamk_ws.data_ptr() : nullptr}); // The launch reserves the whole SMEM capacity, which also keeps multiple diff --git a/csrc/kernel/gemm/kernel_traits.cuh b/csrc/kernel/gemm/kernel_traits.cuh index a91fa80..b847c9d 100644 --- a/csrc/kernel/gemm/kernel_traits.cuh +++ b/csrc/kernel/gemm/kernel_traits.cuh @@ -38,6 +38,8 @@ struct GemmParams { int *__restrict__ masked_m = nullptr; int *__restrict__ expert_ids = nullptr; bool use_pdl = false; + // Batch D layout: false = [M, B * N] (default), true = [B, M, N]. + bool batch_out_bmn = false; void *__restrict__ ptr_sfd = nullptr; void const *__restrict__ ptr_gate = nullptr; int64_t gate_ld = 0; diff --git a/halops/gemm/batch_gemm.py b/halops/gemm/batch_gemm.py index 70fac1e..3c9a686 100644 --- a/halops/gemm/batch_gemm.py +++ b/halops/gemm/batch_gemm.py @@ -66,6 +66,9 @@ def batch_gemm( sfb: [B, N, sf_k] scale factor for B, dtype uint8, same SfAtom layout as sfa. output: [M, B * N] pre-allocated output tensor, dtype bfloat16, or float8_e4m3fn (``w8a8-mxfp8``) for an MXFP8-quantized output. + ``mode="bf16"`` also accepts the contiguous batch-major + ``[B, M, N]`` layout, which writes faster when ``B`` is large and + ``N`` is narrow. bias: Optional [B, N] bfloat16 bias vector. Only supported in w8a8-mxfp8 mode. alpha: Optional float32 per-batch scaling factor with shape [B], one value per batch item. Required for ``w4a4-nvfp4``; not accepted for diff --git a/tests/test_gemm_bf16_grouped.py b/tests/test_gemm_bf16_grouped.py index b27c97e..3fe689f 100644 --- a/tests/test_gemm_bf16_grouped.py +++ b/tests/test_gemm_bf16_grouped.py @@ -76,6 +76,30 @@ def test_batch_bf16_large_m(): _run_batch_bf16(B=4, M=1024, N=256, K=128) +def _run_batch_bf16_bmn(B, M, N, K): + """Batch-major [B, M, N] output, the layout large-B callers want.""" + print(f"[BF16 batch bmn] B={B}, M={M}, N={N}, K={K}") + x = torch.randn([B, M, K], dtype=torch.bfloat16) + w = torch.randn([B, N, K], dtype=torch.bfloat16) + out = torch.zeros([B, M, N], dtype=torch.bfloat16) + + ref = torch.matmul( + x.to(torch.float32), w.to(torch.float32).transpose(1, 2) + ).to(torch.bfloat16) + + batch_gemm(x, w, None, None, out, mode="bf16") + + for b in range(B): + _assert_close(out[b], ref[b], f"batch-bmn {b}") + print(f" [PASS] BF16 batch bmn B={B}, M={M}, N={N}, K={K}") + + +def test_batch_bf16_bmn_layout(): + # Small B (model-shaped) and a large-B / narrow-N case: B * N rows. + _run_batch_bf16_bmn(B=4, M=128, N=256, K=128) + _run_batch_bf16_bmn(B=512, M=64, N=256, K=64) + + # ===================================================================== # Grouped masked GEMM (BF16) # ===================================================================== @@ -164,6 +188,7 @@ def test_contiguous_bf16_mid_m(): print("=" * 60) test_batch_bf16_mid_m() test_batch_bf16_large_m() + test_batch_bf16_bmn_layout() test_masked_bf16_mid_m() test_contiguous_bf16_mid_m() print("\n" + "=" * 60) From de7c6d26c150703404089dd8f2475c2d39c06c82 Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Tue, 10 Nov 2026 21:40:28 +0800 Subject: [PATCH 06/14] bench(gemm): measure bf16 batch with the batch-major [B, M, N] output The benchmark driver fed HALOps the default [M, B * N] output while every reference backend (bmm, flashinfer) writes [B, M, N]. Now that the bf16 batch epilogue also accepts the batch-major layout, drive all backends with the same tensor: fewer layouts to reason about, and the reported numbers match the layout large-B callers should use. Re-recorded all nine batch_bf16 CI entries from two runs (+-0.5% apart): no shape regressed, the two short-K shapes improved by 7.7% and 2.8% ([8192,64,512,64] 214.2 -> 198.0 us, [8192,64,256,64] 108.0 -> 105.0 us), and the remaining seven moved by <= 1.7%. The default [M, B * N] path keeps its own numbers in the previous commit; CI now guards this one. Co-Authored-By: Claude Code --- benchmark/kernel/gemm/scenarios/batch_gemm.py | 10 +++------- ci/baselines/gemm/batch_bf16.json | 18 +++++++++--------- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/benchmark/kernel/gemm/scenarios/batch_gemm.py b/benchmark/kernel/gemm/scenarios/batch_gemm.py index eda2257..5dc733a 100644 --- a/benchmark/kernel/gemm/scenarios/batch_gemm.py +++ b/benchmark/kernel/gemm/scenarios/batch_gemm.py @@ -63,8 +63,7 @@ class BatchGemmInput: x: torch.Tensor # [B, M, K] bfloat16 w: torch.Tensor # [B, N, K] bfloat16 - out: torch.Tensor # [B, M, N] bfloat16 (torch.bmm / flashinfer layout) - out_halops: torch.Tensor # [M, B * N] bfloat16 (HALOps batch_gemm layout) + out: torch.Tensor # [B, M, N] bfloat16 b: int m: int n: int @@ -84,13 +83,11 @@ def _build_inputs( x = torch.randn(b, m, k, dtype=torch.bfloat16, device=dev) w = torch.randn(b, n, k, dtype=torch.bfloat16, device=dev) out = torch.empty(b, m, n, dtype=torch.bfloat16, device=dev) - out_halops = torch.empty(m, b * n, dtype=torch.bfloat16, device=dev) return BatchGemmInput( x=x, w=w, out=out, - out_halops=out_halops, b=b, m=m, n=n, @@ -105,7 +102,7 @@ def adapt_halops(inp: BatchGemmInput) -> dict: return { "x": inp.x, "w": inp.w, - "out": inp.out_halops, + "out": inp.out, "sfa": None, "sfb": None, "bias": None, @@ -234,9 +231,8 @@ def _refcheck_entry( inp["out"].zero_() run_fn(inp) torch.cuda.synchronize() + # Every backend writes the [B, M, N] layout. out = inp["out"] - if out.dim() == 2: # HALOps writes [M, B * N] - out = out.view(m, b, n).transpose(0, 1) diff = (out.float() - ref_out.float()).abs() tol = refcheck_atol + refcheck_rtol * ref_out.float().abs() n_bad = (diff > tol).sum().item() diff --git a/ci/baselines/gemm/batch_bf16.json b/ci/baselines/gemm/batch_bf16.json index d7345b7..b1a4265 100644 --- a/ci/baselines/gemm/batch_bf16.json +++ b/ci/baselines/gemm/batch_bf16.json @@ -15,7 +15,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 348.236 + "median_us": 347.946 }, { "key": { @@ -29,7 +29,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 1888.814 + "median_us": 1859.059 }, { "key": { @@ -43,7 +43,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 912.394 + "median_us": 900.468 }, { "key": { @@ -57,7 +57,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 214.245 + "median_us": 197.99 }, { "key": { @@ -71,7 +71,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 107.999 + "median_us": 105.0 }, { "key": { @@ -85,7 +85,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 184.657 + "median_us": 183.725 }, { "key": { @@ -99,7 +99,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 64.24 + "median_us": 64.047 }, { "key": { @@ -113,7 +113,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 62.082 + "median_us": 62.184 }, { "key": { @@ -127,7 +127,7 @@ "mode": "bf16", "case_tag": "batch_bf16" }, - "median_us": 170.864 + "median_us": 170.431 } ] } \ No newline at end of file From 26e87ed324c0bf92bb5b98502fc06b8e69c241e6 Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 19 Nov 2026 10:20:20 +0800 Subject: [PATCH 07/14] test(gemm): fold BF16 cases into the per-entry GEMM test files Review feedback on the BF16 GEMM commit: the two dedicated test files were a separate suite with their own conventions. Move every case into the test file that already covers its entry point, so BF16 is just another mode there rather than a parallel suite. - test_dense_gemm.py: make_mode_inputs / make_empty_inputs gain a "bf16" branch; test_gemm_bf16 parametrizes the twelve shapes the old file ran (large-M, the N=1600 predicated tail at every M rung, large-M narrow N, mid-M, odd N, SwapAB, deep K); the bad-K case joins the shared unsupported-shape table. - test_batch_gemm.py: cases for the default [M, B * N] output and the batch-major [B, M, N] one, reusing assert_close_per_batch. - test_group_masked_gemm.py / test_group_contiguous_gemm.py: one BF16 case each, reusing the existing wrappers and comparison helpers. - gemm_utils.py: BF16_TOL next to the FP8/FP4 tolerances. - Delete tests/test_gemm_bf16.py and test_gemm_bf16_grouped.py: they set the seed and default device a second time, debug-printed, and hand-rolled the runtime-error assertion, all of which the shared fixtures and pytest.raises already cover. Also adds the missing test for the sfa/sfb-required check that the std::optional refactor introduced on the quantized branches. Verified: the four files pass (183 passed, 2 xfailed; the xfails are the pre-existing w4a8 masked sub-64 swap cases). Co-Authored-By: Claude Code --- tests/test_batch_gemm.py | 57 ++++++++ tests/test_dense_gemm.py | 89 +++++++++++++ tests/test_gemm_bf16.py | 131 ------------------- tests/test_gemm_bf16_grouped.py | 196 ---------------------------- tests/test_group_contiguous_gemm.py | 35 +++++ tests/test_group_masked_gemm.py | 41 ++++++ tests/utils/gemm_utils.py | 1 + 7 files changed, 223 insertions(+), 327 deletions(-) delete mode 100644 tests/test_gemm_bf16.py delete mode 100644 tests/test_gemm_bf16_grouped.py diff --git a/tests/test_batch_gemm.py b/tests/test_batch_gemm.py index cd3e468..2e567ca 100644 --- a/tests/test_batch_gemm.py +++ b/tests/test_batch_gemm.py @@ -23,6 +23,7 @@ from tests.utils.fp4_utils import MXFP4_BLOCK_SIZE, NVFP4_BLOCK_SIZE from tests.utils.gemm_utils import ( + BF16_TOL, W4A4_TOL, W8A8_MXFP8_TOL, per_block_cast_to_nvfp4, @@ -100,6 +101,15 @@ def ref_batch_gemm_fp4(x_fp4_float, w_fp4_float): return output +def ref_batch_gemm_bf16(x, w): + """BF16 Batch GEMM reference: fp32 x[b] @ w[b]^T rounded to bf16, [B, M, N]. + x: [B, M, K] bfloat16, w: [B, N, K] bfloat16 + """ + return torch.matmul(x.to(torch.float32), w.to(torch.float32).transpose(1, 2)).to( + torch.bfloat16 + ) + + # ===================================================================== # Input builders # ===================================================================== @@ -715,5 +725,52 @@ def test_batch_gemm_mxfp4_determinism(): assert torch.equal(out1, out2), "MXFP4 batch_gemm output is not deterministic" +# ===================================================================== +# BF16 correctness tests +# ===================================================================== + + +def make_bf16_inputs(B, M, N, K): + x = torch.randn([B, M, K], dtype=torch.bfloat16) + w = torch.randn([B, N, K], dtype=torch.bfloat16) + return x, w, ref_batch_gemm_bf16(x, w) + + +@pytest.mark.parametrize( + "B, M, N, K", + [ + pytest.param(4, 128, 256, 128, id="mid_m"), + pytest.param(4, 1024, 256, 128, id="large_m"), + ], +) +def test_batch_gemm_bf16(B, M, N, K): + x, w, ref_out = make_bf16_inputs(B, M, N, K) + output = torch.zeros([M, B * N], dtype=torch.bfloat16) + batch_gemm(x, w, None, None, output, mode="bf16") + assert_close_per_batch( + output, ref_out, BF16_TOL, f"BF16 B={B}, M={M}, N={N}, K={K}" + ) + + +@pytest.mark.parametrize( + "B, M, N, K", + [ + pytest.param(4, 128, 256, 128, id="small_b"), + pytest.param(512, 64, 256, 64, id="large_b_narrow_n"), + ], +) +def test_batch_gemm_bf16_batch_major_output(B, M, N, K): + """mode="bf16" also accepts a contiguous [B, M, N] output.""" + x, w, ref_out = make_bf16_inputs(B, M, N, K) + output = torch.zeros([B, M, N], dtype=torch.bfloat16) + batch_gemm(x, w, None, None, output, mode="bf16") + torch.testing.assert_close( + output.to(torch.float32), + ref_out.to(torch.float32), + **BF16_TOL, + msg=lambda s: f"BF16 [B, M, N] B={B}, M={M}, N={N}, K={K}: {s}", + ) + + if __name__ == "__main__": pytest.main([__file__]) diff --git a/tests/test_dense_gemm.py b/tests/test_dense_gemm.py index 0321dec..a9e9311 100644 --- a/tests/test_dense_gemm.py +++ b/tests/test_dense_gemm.py @@ -23,6 +23,7 @@ from tests.utils.fp4_utils import MXFP4_BLOCK_SIZE, NVFP4_BLOCK_SIZE from tests.utils.gemm_utils import ( + BF16_TOL, W4A4_TOL, W8A8_MXFP8_TOL, per_block_cast_to_nvfp4, @@ -74,6 +75,11 @@ def ref_gemm_w4a4(x_fp4_float, w_fp4_float): return torch.matmul(x_fp4_float, w_fp4_float.T).to(torch.bfloat16) +def ref_gemm_bf16(x, w): + """Reference BF16 GEMM: fp32 matmul of x (m, k) and w (n, k), rounded to bf16.""" + return torch.matmul(x.to(torch.float32), w.to(torch.float32).T).to(torch.bfloat16) + + # ===================================================================== # Kernel invocation and input builders # ===================================================================== @@ -172,6 +178,10 @@ def make_empty_inputs(m, n, k, mode, x_shape=None, out_shape=None): sfa = torch.empty([m, k // 16], dtype=torch.uint8) sfb = torch.empty([n, k // 16], dtype=torch.uint8) alpha = torch.ones([1], dtype=torch.float32) + elif mode == "bf16": + x = torch.empty(x_shape or [m, k], dtype=torch.bfloat16) + w = torch.empty([n, k], dtype=torch.bfloat16) + sfa = sfb = alpha = None else: raise ValueError(f"Unsupported mode for empty inputs: {mode!r}") out = torch.empty(out_shape or [m, n], dtype=torch.bfloat16) @@ -425,6 +435,69 @@ def test_gemm_mxfp4_bad_scale_shape(): dense_gemm(x, w, sfa, sfb, out, None, None, -1, "w4a4-mxfp4") +# ===================================================================== +# BF16 tests +# ===================================================================== + + +@pytest.mark.parametrize( + "m, n, k", + [ + pytest.param(4096, 256, 256, id="large_m-4096x256x256"), + # 1600 % 128 == 64: the 256x128 predicated N-tail tile, at every M rung. + pytest.param(1024, 1600, 4096, id="ntail-1024x1600x4096"), + pytest.param(2048, 1600, 4096, id="ntail-2048x1600x4096"), + pytest.param(4096, 1600, 4096, id="ntail-4096x1600x4096"), + pytest.param(8192, 1600, 4096, id="ntail-8192x1600x4096"), + pytest.param(16384, 1600, 4096, id="ntail-16384x1600x4096"), + # The 256-wide family underfills a wave, so large M steps down to 64xN. + pytest.param(4096, 128, 4096, id="large_m_n128-4096x128x4096"), + pytest.param(8192, 128, 4096, id="large_m_n128-8192x128x4096"), + pytest.param(128, 256, 256, id="mid_m-128x256x256"), + pytest.param(1024, 1536, 4096, id="mid_m_odd_n-1024x1536x4096"), + pytest.param(64, 256, 256, id="small_m_swapab-64x256x256"), + pytest.param(64, 4096, 8192, id="small_m_deep_k-64x4096x8192"), + ], +) +def test_gemm_bf16(m, n, k): + output, ref_out, tol = run_mode_gemm("bf16", m, n, k) + torch.testing.assert_close( + output.to(torch.float32), + ref_out.to(torch.float32), + **tol, + msg=lambda s: f"BF16 dense_gemm m={m}, n={n}, k={k}: {s}", + ) + + +def test_gemm_bf16_rejects_non_bf16_input(): + x, w, _, _, out, _ = make_empty_inputs(128, 256, 256, "bf16") + with pytest.raises(RuntimeError, match=re.escape("input must be bfloat16")): + dense_gemm(x.half(), w, None, None, out, None, None, -1, "bf16") + + +def test_gemm_bf16_rejects_epilogue_op(): + x, w, _, _, out, _ = make_empty_inputs(128, 256, 256, "bf16") + with pytest.raises( + RuntimeError, match=re.escape("supports EpilogueOp.Identity only") + ): + dense_gemm( + x, w, None, None, out, None, None, -1, "bf16", False, EpilogueOp.Sigmoid + ) + + +@pytest.mark.parametrize( + "mode, expected", + [ + ("w8a8-mxfp8", "w8a8-mxfp8 dense GEMM requires sfa/sfb scale factors"), + ("w4a4-nvfp4", "W4A4 dense GEMM requires sfa/sfb scale factors"), + ], +) +def test_gemm_quant_requires_scale_factors(mode, expected): + x, w, _, _, out, alpha = make_empty_inputs(128, 256, 256, mode) + with pytest.raises(RuntimeError, match=re.escape(expected)): + dense_gemm(x, w, None, None, out, None, alpha, -1, mode) + + # ===================================================================== # Unsupported shapes # ===================================================================== @@ -464,6 +537,16 @@ def test_gemm_mxfp4_bad_scale_shape(): "No dense w4a4-nvfp4 tile for M=128 (grid M=128), N=256, K=48", id="nvfp4_bad_k", ), + pytest.param( + "bf16", + 128, + 256, + 96, + None, + None, + "BF16 GEMM mid M K must be divisible by 64", + id="bf16_bad_k", + ), pytest.param( "w8a8-mxfp8", 128, @@ -531,6 +614,12 @@ def test_gemm_nvfp4_determinism(): def make_mode_inputs(mode, m, n, k): """Build the kernel arguments, reference output and tolerance for ``mode``.""" + if mode == "bf16": + x = torch.randn([m, k], dtype=torch.bfloat16) + w = torch.randn([n, k], dtype=torch.bfloat16) + ref_out = ref_gemm_bf16(x, w) + return (x, w, None, None), {}, ref_out, BF16_TOL + if mode == "w8a8-mxfp8": inp = make_w8a8_mxfp8_inputs(m, n, k) ref_out = ref_gemm(inp["x"], inp["w"], inp["sfa_logical"], inp["sfb_logical"]) diff --git a/tests/test_gemm_bf16.py b/tests/test_gemm_bf16.py deleted file mode 100644 index 2d2dc99..0000000 --- a/tests/test_gemm_bf16.py +++ /dev/null @@ -1,131 +0,0 @@ -""" -# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. - -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at - -# http://www.apache.org/licenses/LICENSE-2.0 - -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" - -import numpy as np -import torch - -from halops import dense_gemm - - -torch.manual_seed(2026) -torch.cuda.manual_seed_all(2026) -torch.set_default_device("cuda") - - -def _run_bf16_gemm_case(m, n, k): - print(f"[BF16 GEMM] m={m}, n={n}, k={k}") - x = torch.randn([m, k], dtype=torch.bfloat16) - w = torch.randn([n, k], dtype=torch.bfloat16) - out = torch.empty([m, n], dtype=torch.bfloat16) - - ref = torch.matmul(x.to(torch.float32), w.to(torch.float32).T).to(torch.bfloat16) - dense_gemm(x, w, None, None, out, mode="bf16") - - diff = (out.to(torch.float32) - ref.to(torch.float32)).abs() - print( - f"[BF16 GEMM] max_diff={diff.max().item():.6f}, " - f"mean_diff={diff.mean().item():.6f}" - ) - np.testing.assert_allclose( - out.to(torch.float32).cpu().numpy(), - ref.to(torch.float32).cpu().numpy(), - rtol=2e-2, - atol=2e-2, - ) - - -def _expect_runtime_error(fn, expected): - try: - fn() - except RuntimeError as e: - msg = str(e) - assert expected in msg, f"expected '{expected}' in RuntimeError, got: {msg}" - print(f" [PASS] caught expected RuntimeError: {expected}") - else: - raise AssertionError(f"expected RuntimeError containing: {expected}") - - -def test_bf16_gemm_large_m(): - _run_bf16_gemm_case(4096, 256, 256) - - -def test_bf16_gemm_large_m_n1600(): - # 1600 % 128 == 64: exercises the 256x128 predicated-tail tile end to end. - _run_bf16_gemm_case(4096, 1600, 4096) - - -def test_bf16_gemm_large_m_n1600_ladder(): - # N=1600 across every M rung of benchmark/configs/gemm/dense_bf16.yaml. - for m in (1024, 2048, 4096, 8192, 16384): - _run_bf16_gemm_case(m, 1600, 4096) - - -def test_bf16_gemm_large_m_n128(): - # n=128: the 256-wide family underfills a wave, so large-M steps M down - # (64x64 / 64x128 rungs). - _run_bf16_gemm_case(4096, 128, 4096) - _run_bf16_gemm_case(8192, 128, 4096) - - -def test_bf16_gemm_mid_m(): - _run_bf16_gemm_case(128, 256, 256) - - -def test_bf16_gemm_small_m(): - # m < 128 -> 128x64x64 SwapAB small-M path. - # SwapAB: weight is the 128-wide MMA M, the activation the 64-wide N. - _run_bf16_gemm_case(64, 256, 256) - - -def test_bf16_gemm_small_m_deep_k(): - # thin-M with k >= 8192 -> 128x64x128 SwapAB rung (KBlockK=128). - _run_bf16_gemm_case(64, 4096, 8192) - - -def test_bf16_gemm_mid_m_odd_n(): - # N not a multiple of 128 -> mid-M 64x96 rung / predicated tail family. - _run_bf16_gemm_case(1024, 1536, 4096) - - -def test_bf16_gemm_unsupported_shapes(): - def run_bad_k(): - m, n, k = 128, 256, 96 - x = torch.empty([m, k], dtype=torch.bfloat16) - w = torch.empty([n, k], dtype=torch.bfloat16) - out = torch.empty([m, n], dtype=torch.bfloat16) - dense_gemm(x, w, None, None, out, mode="bf16") - - _expect_runtime_error(run_bad_k, "BF16 GEMM mid M K must be divisible by 64") - - def run_bad_dtype(): - m, n, k = 128, 256, 256 - x = torch.empty([m, k], dtype=torch.float16) - w = torch.empty([n, k], dtype=torch.bfloat16) - out = torch.empty([m, n], dtype=torch.bfloat16) - dense_gemm(x, w, None, None, out, mode="bf16") - - _expect_runtime_error(run_bad_dtype, "input must be bfloat16") - - -if __name__ == "__main__": - test_bf16_gemm_large_m() - test_bf16_gemm_large_m_n1600() - test_bf16_gemm_large_m_n1600_ladder() - test_bf16_gemm_large_m_n128() - test_bf16_gemm_mid_m() - test_bf16_gemm_small_m() - test_bf16_gemm_unsupported_shapes() - print("All BF16 GEMM tests passed!") diff --git a/tests/test_gemm_bf16_grouped.py b/tests/test_gemm_bf16_grouped.py deleted file mode 100644 index 3fe689f..0000000 --- a/tests/test_gemm_bf16_grouped.py +++ /dev/null @@ -1,196 +0,0 @@ -""" -# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. - -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at - -# http://www.apache.org/licenses/LICENSE-2.0 - -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" - -# Native BF16 accuracy tests for the batch / grouped entry points. They take -# the KIsBF16 branch (no scale factors, no alpha) of the shared mainloop. The -# golden reference is an fp32 matmul rounded to bf16, so tolerances are tighter -# than for the quantized paths. - -import numpy as np -import torch - -from halops import batch_gemm, group_contiguous_gemm, group_masked_gemm - -torch.manual_seed(2026) -torch.cuda.manual_seed_all(2026) -torch.set_default_device("cuda") - -# Output is rounded once by the kernel and once by the reference; a couple of -# ulps suffice. There is no dequantization error, so this is far tighter than -# fp8 in relative terms. -RTOL = 1e-2 -ATOL = 1e-2 - - -def _assert_close(out, ref, tag): - out_np = out.to(torch.float32).cpu().numpy() - ref_np = ref.to(torch.float32).cpu().numpy() - diff = np.abs(out_np - ref_np) - print(f" {tag}: max_diff={diff.max():.6f}, mean_diff={diff.mean():.6f}") - np.testing.assert_allclose(out_np, ref_np, rtol=RTOL, atol=ATOL) - - -# ===================================================================== -# Batch GEMM (BF16) -# ===================================================================== - - -def _run_batch_bf16(B, M, N, K): - print(f"[BF16 batch] B={B}, M={M}, N={N}, K={K}") - x = torch.randn([B, M, K], dtype=torch.bfloat16) - w = torch.randn([B, N, K], dtype=torch.bfloat16) - out = torch.zeros([M, B * N], dtype=torch.bfloat16) - - # Golden: per-batch fp32 matmul, output[:, b * N:(b + 1) * N] = x[b] @ w[b]^T - ref = torch.matmul(x.to(torch.float32), w.to(torch.float32).transpose(1, 2)).to( - torch.bfloat16 - ) - - batch_gemm(x, w, None, None, out, mode="bf16") - - for b in range(B): - _assert_close(out[:, b * N : (b + 1) * N], ref[b], f"batch {b}") - print(f" [PASS] BF16 batch B={B}, M={M}, N={N}, K={K}") - - -def test_batch_bf16_mid_m(): - # total_m = 512 -> 128x256x64 mid path - _run_batch_bf16(B=4, M=128, N=256, K=128) - - -def test_batch_bf16_large_m(): - # total_m = 4096 -> 256x256x64 large path - _run_batch_bf16(B=4, M=1024, N=256, K=128) - - -def _run_batch_bf16_bmn(B, M, N, K): - """Batch-major [B, M, N] output, the layout large-B callers want.""" - print(f"[BF16 batch bmn] B={B}, M={M}, N={N}, K={K}") - x = torch.randn([B, M, K], dtype=torch.bfloat16) - w = torch.randn([B, N, K], dtype=torch.bfloat16) - out = torch.zeros([B, M, N], dtype=torch.bfloat16) - - ref = torch.matmul( - x.to(torch.float32), w.to(torch.float32).transpose(1, 2) - ).to(torch.bfloat16) - - batch_gemm(x, w, None, None, out, mode="bf16") - - for b in range(B): - _assert_close(out[b], ref[b], f"batch-bmn {b}") - print(f" [PASS] BF16 batch bmn B={B}, M={M}, N={N}, K={K}") - - -def test_batch_bf16_bmn_layout(): - # Small B (model-shaped) and a large-B / narrow-N case: B * N rows. - _run_batch_bf16_bmn(B=4, M=128, N=256, K=128) - _run_batch_bf16_bmn(B=512, M=64, N=256, K=64) - - -# ===================================================================== -# Grouped masked GEMM (BF16) -# ===================================================================== - - -def _run_masked_bf16(num_experts, max_m_per_expert, N, K, masked_m): - print( - f"[BF16 masked] experts={num_experts}, max_m={max_m_per_expert}, " - f"N={N}, K={K}, masked_m={masked_m}" - ) - total_m = num_experts * max_m_per_expert - x = torch.randn([total_m, K], dtype=torch.bfloat16) - w = torch.randn([num_experts, N, K], dtype=torch.bfloat16) - out = torch.zeros([total_m, N], dtype=torch.bfloat16) - masked_m_t = torch.tensor(masked_m, dtype=torch.int32) - - group_masked_gemm( - x, - w, - None, - None, - masked_m_t, - out, - max_m_per_expert=max_m_per_expert, - mode="bf16", - ) - - # Golden + comparison per expert, valid rows only. - for e in range(num_experts): - m = masked_m[e] - if m == 0: - continue - start = e * max_m_per_expert - x_e = x[start : start + m, :].to(torch.float32) - w_e = w[e].to(torch.float32).T - ref_e = torch.matmul(x_e, w_e).to(torch.bfloat16) - _assert_close(out[start : start + m, :], ref_e, f"expert {e} (m={m})") - print(f" [PASS] BF16 masked experts={num_experts}, max_m={max_m_per_expert}") - - -def test_masked_bf16_mid_m(): - # max_m_per_expert = 128 -> 128x256x64 mid path; masked_m < max exercises masking - _run_masked_bf16( - num_experts=2, max_m_per_expert=128, N=256, K=128, masked_m=[100, 128] - ) - - -# ===================================================================== -# Grouped contiguous GEMM (BF16) -# ===================================================================== - - -def _run_contiguous_bf16(token_nums, N, K): - num_experts = len(token_nums) - m = int(sum(token_nums)) - print(f"[BF16 contiguous] m={m}, N={N}, K={K}, token_nums={token_nums}") - x = torch.randn([m, K], dtype=torch.bfloat16) - w = torch.randn([num_experts, N, K], dtype=torch.bfloat16) - out = torch.zeros([m, N], dtype=torch.bfloat16) - - ids = np.concatenate( - [np.full(c, e, dtype=np.int32) for e, c in enumerate(token_nums)] - ) - expert_ids = torch.tensor(ids, dtype=torch.int32) - - group_contiguous_gemm(x, w, None, None, expert_ids, out, mode="bf16") - - offset = 0 - for e, c in enumerate(token_nums): - x_e = x[offset : offset + c, :].to(torch.float32) - w_e = w[e].to(torch.float32).T - ref_e = torch.matmul(x_e, w_e).to(torch.bfloat16) - _assert_close(out[offset : offset + c, :], ref_e, f"expert {e} (m={c})") - offset += c - print(f" [PASS] BF16 contiguous m={m}, experts={num_experts}") - - -def test_contiguous_bf16_mid_m(): - # Each expert's token count aligned to tile_m=128; m=512 -> 128x256x64 path. - _run_contiguous_bf16(token_nums=[256, 256], N=256, K=128) - - -if __name__ == "__main__": - print("=" * 60) - print("BF16 batch / grouped GEMM tests") - print("=" * 60) - test_batch_bf16_mid_m() - test_batch_bf16_large_m() - test_batch_bf16_bmn_layout() - test_masked_bf16_mid_m() - test_contiguous_bf16_mid_m() - print("\n" + "=" * 60) - print("All BF16 batch/grouped GEMM tests passed!") - print("=" * 60) diff --git a/tests/test_group_contiguous_gemm.py b/tests/test_group_contiguous_gemm.py index c1ea69a..8066316 100644 --- a/tests/test_group_contiguous_gemm.py +++ b/tests/test_group_contiguous_gemm.py @@ -25,6 +25,7 @@ from tests.utils.fp4_utils import MXFP4_BLOCK_SIZE, NVFP4_BLOCK_SIZE from tests.utils.gemm_utils import ( + BF16_TOL, W4A4_TOL, W8A8_MXFP8_TOL, per_block_cast_to_nvfp4, @@ -133,6 +134,20 @@ def ref_group_contiguous_gemm_w4a4(x_fp4_float, w_fp4_float, expert_ids, num_exp return ref_out +def ref_group_contiguous_gemm_bf16(x, w, expert_ids, num_experts): + """ + Reference implementation of BF16 grouped contiguous GEMM. + x: (M, K) bfloat16, w: (num_experts, N, K) bfloat16, expert_ids: (M,) int32 + """ + ref_out = torch.zeros([x.shape[0], w.shape[1]], dtype=torch.bfloat16) + for expert_id in range(num_experts): + rows = expert_ids == expert_id + ref_out[rows] = torch.matmul( + x[rows].to(torch.float32), w[expert_id].to(torch.float32).T + ).to(torch.bfloat16) + return ref_out + + # ===================================================================== # Kernel invocation and input construction # ===================================================================== @@ -486,6 +501,26 @@ def test_group_contiguous_w4a8_mxfp4(m, n, k, num_experts, tile_m): assert_close_per_expert(output, ref_out, inp.token_nums, W4A4_TOL) +# ===================================================================== +# BF16 accuracy tests +# ===================================================================== + + +@pytest.mark.parametrize( + "m, n, k, num_experts, tile_m", + [pytest.param(512, 256, 128, 2, 128, id="mid_m_e2")], +) +def test_group_contiguous_bf16(m, n, k, num_experts, tile_m): + expert_ids, token_nums, num_experts = make_contiguous_expert_ids( + m, num_experts, tile_m + ) + x = torch.randn([m, k], dtype=torch.bfloat16) + w = torch.randn([num_experts, n, k], dtype=torch.bfloat16) + ref_out = ref_group_contiguous_gemm_bf16(x, w, expert_ids, num_experts) + output = group_contiguous_gemm_wrapper(x, w, None, None, expert_ids, mode="bf16") + assert_close_per_expert(output, ref_out, token_nums, BF16_TOL) + + # ===================================================================== # Unsupported-input checks # ===================================================================== diff --git a/tests/test_group_masked_gemm.py b/tests/test_group_masked_gemm.py index 386e41d..d764970 100644 --- a/tests/test_group_masked_gemm.py +++ b/tests/test_group_masked_gemm.py @@ -25,6 +25,7 @@ from tests.utils.fp4_utils import MXFP4_BLOCK_SIZE, NVFP4_BLOCK_SIZE from tests.utils.gemm_utils import ( + BF16_TOL, W4A4_TOL, W8A8_MXFP8_TOL, per_block_cast_to_nvfp4, @@ -182,6 +183,26 @@ def ref_group_masked_gemm_w4a4( return ref_out +def ref_group_masked_gemm_bf16(x, w, masked_m, max_m_per_expert, num_experts): + """ + Reference implementation of BF16 grouped masked GEMM. + Each expert's valid rows get an fp32 matmul rounded to bf16; masked rows stay 0. + + Parameters: + x: (M_total, K), bfloat16 + w: (num_experts, N, K), bfloat16 + masked_m: (num_experts,), int + """ + ref_out = torch.zeros([x.shape[0], w.shape[1]], dtype=torch.bfloat16) + for expert_id in range(num_experts): + start = expert_id * max_m_per_expert + end = start + int(masked_m[expert_id]) + ref_out[start:end] = torch.matmul( + x[start:end].to(torch.float32), w[expert_id].to(torch.float32).T + ).to(torch.bfloat16) + return ref_out + + # ===================================================================== # Kernel invocation and input construction # ===================================================================== @@ -676,6 +697,26 @@ def test_group_masked_w4a8_mxfp4(max_m_per_expert, num_experts, n, k, full_x, ma ) +# ===================================================================== +# BF16 accuracy tests +# ===================================================================== + + +@pytest.mark.parametrize( + "max_m_per_expert, num_experts, n, k, masked_m", + [pytest.param(128, 2, 256, 128, [100, 128], id="mid_m_partial_mask")], +) +def test_group_masked_bf16(max_m_per_expert, num_experts, n, k, masked_m): + x = torch.randn([num_experts * max_m_per_expert, k], dtype=torch.bfloat16) + w = torch.randn([num_experts, n, k], dtype=torch.bfloat16) + masked_m = torch.tensor(masked_m, dtype=torch.int32) + ref_out = ref_group_masked_gemm_bf16(x, w, masked_m, max_m_per_expert, num_experts) + output = group_masked_gemm_wrapper( + x, w, None, None, masked_m, max_m_per_expert, mode="bf16" + ) + assert_close_per_expert(output, ref_out, masked_m, max_m_per_expert, BF16_TOL) + + # ===================================================================== # Unsupported-input checks # ===================================================================== diff --git a/tests/utils/gemm_utils.py b/tests/utils/gemm_utils.py index 8a05a61..6ae1eb6 100644 --- a/tests/utils/gemm_utils.py +++ b/tests/utils/gemm_utils.py @@ -28,6 +28,7 @@ W8A8_MXFP8_TOL = dict(rtol=2e-2, atol=2e-3) MXFP8_BLOCK_SIZE = 32 W4A4_TOL = dict(rtol=5e-2, atol=5e-2) +BF16_TOL = dict(rtol=1e-2, atol=1e-2) # ===================================================================== # FP8 (W8A8-MXFP8) quantization helpers From 971e37997b68ec7773d6985e7f687b30b69cf9e8 Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 19 Nov 2026 10:20:27 +0800 Subject: [PATCH 08/14] refactor(gemm): route BF16 through the shared LaunchCfg Review feedback on the BF16 GEMM commit: the BF16 windows had their own launch helpers and shape plumbing, so the four entry points looked unlike the quantized ones and the per-tile validation lived in a second place. - Dispatch: CandidateTilesFor is the one place a kind maps to its candidate table (BF16 picks a table per mode, everything else keeps CandidateTiles). LaunchCfg takes the pick from bf16::PickBf16Tile for BF16 and from the cost model otherwise, so dense, batch, contiguous and masked all read `LaunchCfg(params, shape, stream)`. LaunchSelected and the four Launch* helpers are gone. - The tile divisibility check moves into LaunchTile, where it runs for every BF16 instantiation instead of only for the ones that went through a launch helper. - The rule ladder itself stays: it encodes measured bands and swapping it for the cost model would need a fresh sweep over every shape. - Drop ResolveSmCount (gemm_utils.h) and use the existing `sm_count > 0 ? sm_count : GetSmCount()` idiom the entry points already follow; drop CheckGemmTileShape, which had no callers. - Drop the comments above epilogue_bf16. Verified: build clean; dense/batch/grouped GEMM tests pass (183 passed, 2 xfailed); ci/test_benchmark.py passes all eight configs within the 5% threshold, so the FP8/FP4 dispatch and the BF16 numbers are unchanged. Co-Authored-By: Claude Code --- csrc/kernel/gemm/batch_gemm.cu | 13 +- csrc/kernel/gemm/dense_gemm.cu | 13 +- csrc/kernel/gemm/epilogue.cuh | 5 - csrc/kernel/gemm/gemm_dispatch.cuh | 185 +++++++++------------- csrc/kernel/gemm/gemm_kernel.cuh | 2 +- csrc/kernel/gemm/gemm_utils.h | 17 -- csrc/kernel/gemm/group_contiguous_gemm.cu | 13 +- csrc/kernel/gemm/group_masked_gemm.cu | 13 +- 8 files changed, 119 insertions(+), 142 deletions(-) diff --git a/csrc/kernel/gemm/batch_gemm.cu b/csrc/kernel/gemm/batch_gemm.cu index c02be29..e0a06c7 100644 --- a/csrc/kernel/gemm/batch_gemm.cu +++ b/csrc/kernel/gemm/batch_gemm.cu @@ -89,8 +89,7 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.batch_out_bmn = bmn_out; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored; dispatch and launch - // live in gemm_dispatch.cuh (bf16::LaunchBatch). + // Native BF16: sfa/sfb/bias/alpha are ignored. const int k = weight.size(2); TORCH_CHECK(input.size(2) == k, "input K must match weight K, got input K=", input.size(2), @@ -110,7 +109,15 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - bf16::LaunchBatch(params, sm, stream); + LaunchCfg( + params, + {.m = m, + .n = n, + .k = k, + .m_grid = m * batches, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 batch GEMM requires sfa/sfb scale factors " diff --git a/csrc/kernel/gemm/dense_gemm.cu b/csrc/kernel/gemm/dense_gemm.cu index cce33ce..ea22090 100644 --- a/csrc/kernel/gemm/dense_gemm.cu +++ b/csrc/kernel/gemm/dense_gemm.cu @@ -73,8 +73,7 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, : 0.0f}; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored; the tile ladder, - // validation and launch live in gemm_dispatch.cuh (bf16::LaunchDense). + // Native BF16: sfa/sfb/bias/alpha are ignored. TORCH_CHECK(input.dtype() == torch::kBFloat16, "bf16 dense GEMM: input must be bfloat16"); TORCH_CHECK(weight.dtype() == torch::kBFloat16, @@ -106,7 +105,15 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, CheckDivisible(m, 64, "BF16 GEMM SwapAB M"); CheckDivisible(k, 64, "BF16 GEMM SwapAB K"); } - bf16::LaunchDense(params, sm, stream); + LaunchCfg( + params, + {.m = m, + .n = n, + .k = k, + .m_grid = m, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 dense GEMM requires sfa/sfb scale factors " diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index b46efcb..eba88b4 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -727,11 +727,6 @@ class CollectiveEpilogue { } } - - // BF16 path: TMEM -> registers -> cast -> GMEM through CuTe tiled copies, - // which follow the 16dp (64-row CTA) and 2SM "2x2" accumulator layouts. - // KStreamK: compile-time stream-K instantiation; a runtime branch here - // would spill the data-parallel store path. template CUTLASS_DEVICE void epilogue_bf16(Params const& epilogue_params, AccumulatorPipeline& acc_pipeline, diff --git a/csrc/kernel/gemm/gemm_dispatch.cuh b/csrc/kernel/gemm/gemm_dispatch.cuh index ece205d..4a96a01 100644 --- a/csrc/kernel/gemm/gemm_dispatch.cuh +++ b/csrc/kernel/gemm/gemm_dispatch.cuh @@ -357,9 +357,48 @@ inline int PickTile(const TileSpec* tiles, int count, MmaKind kind, // Dispatch using TileLauncher = void (*)(GemmParams&, const GemmShape&, cudaStream_t); -// Candidates is any type exposing `static constexpr tiles`: -// CandidateTiles for the cost-model tables, or the per-mode BF16 tables -// below. +// Candidates is any type exposing `static constexpr tiles`. Every kind draws +// from one table; BF16 has a separate one per mode. +template +struct CandidateTilesFor { + static constexpr const auto& tiles = CandidateTiles::tiles; +}; +template <> +struct CandidateTilesFor { + static constexpr const auto& tiles = kBF16DenseTiles; +}; +template <> +struct CandidateTilesFor { + static constexpr const auto& tiles = kBF16ContiguousTiles; +}; +template <> +struct CandidateTilesFor { + static constexpr const auto& tiles = kBF16MaskedTiles; +}; +template <> +struct CandidateTilesFor { + static constexpr const auto& tiles = kBF16BatchTiles; +}; + +// Divisibility contract of a selected tile: the output M/N tile multiples +// (N relaxes to %64 for predicated tails and %32 for non-power-of-2 widths), +// K a KBlockK multiple. SwapAB swaps the roles: KBlockM tiles the weight +// (output N), KBlockN the activation (output M). +inline void CheckBF16TileShape(const char* what, const TileSpec& t, int m, + int n, int k) { + const int n_mod = + t.force_ntail ? 64 + : (((t.block_n & (t.block_n - 1)) != 0) ? 32 : t.block_n); + const int m_div = t.swap_ab ? t.block_n : t.block_m; + const int n_div = t.swap_ab ? t.block_m : n_mod; + TORCH_CHECK(m % m_div == 0, what, " requires M to be divisible by ", m_div, + ", got ", m); + TORCH_CHECK(n % n_div == 0, what, " requires N to be divisible by ", n_div, + ", got ", n); + TORCH_CHECK(k % t.block_k == 0, what, " requires K to be divisible by ", + t.block_k, ", got ", k); +} + template void LaunchTile(GemmParams& params, const GemmShape& shape, @@ -368,6 +407,9 @@ void LaunchTile(GemmParams& params, const GemmShape& shape, if constexpr (TileAllowedFor(S, Mode) && (!IsQuantOp(Op) || (Kind == MmaKind::MXFP8 && S.quantizes()))) { + if constexpr (Kind == MmaKind::BF16) { + CheckBF16TileShape("BF16 GEMM", S, shape.m, shape.n, shape.k); + } using T = MmaTraits; using TypeD = cute::conditional_t; @@ -389,7 +431,7 @@ constexpr std::array MakeTileLaunchers( } template > + class Candidates = CandidateTilesFor> inline constexpr auto kTileLaunchers = MakeTileLaunchers( std::make_index_sequence{}); @@ -399,13 +441,21 @@ inline bool GemmTraceEnabled() { return on; } +// BF16 picks from its rule ladder instead of the cost model; defined with the +// ladder below. +namespace bf16 { +int PickBf16Tile(KernelMode mode, const GemmShape& shape); +} // namespace bf16 + template void LaunchCfg(GemmParams& params, GemmShape shape, cudaStream_t stream) { shape.op = Op; - constexpr auto& candidates = CandidateTiles::tiles; + constexpr auto& candidates = CandidateTilesFor::tiles; const int pick = - PickTile(candidates.data(), static_cast(candidates.size()), Kind, - shape, Mode); + Kind == MmaKind::BF16 + ? bf16::PickBf16Tile(Mode, shape) + : PickTile(candidates.data(), static_cast(candidates.size()), + Kind, shape, Mode); TORCH_CHECK(pick >= 0, "No ", ModeName(Mode), " ", MmaTraits::kName, " tile for M=", shape.m, " (grid M=", shape.m_grid, "), N=", shape.n, ", K=", shape.k, @@ -429,8 +479,8 @@ void LaunchCfg(GemmParams& params, GemmShape shape, cudaStream_t stream) { // BF16 dispatch. Rule-based rather than cost-model based: the ladder below // encodes measured launch-shape bands (pair-UMMA gates, wave-fill judgements, // K-tile depth gates). A selector returns an index into the per-mode tile -// tables in gemm_tile.cuh, or -1 when no tile supports the shape; the launch -// helpers validate the selected tile and run it. +// tables in gemm_tile.cuh, or -1 when no tile supports the shape; +// PickBf16Tile feeds that index to the shared LaunchCfg. // =========================================================================== namespace bf16 { @@ -467,7 +517,7 @@ inline bool SkipSwapForThinM(int m, int n, int k, int sm_count) { if (m % 64 != 0 || k % 64 != 0) { return false; } - const int target = ResolveSmCount(sm_count); + const int target = sm_count > 0 ? sm_count : GetSmCount(); const int mt = CeilDiv(m, 64); const bool narrow_ok = (n % 32 == 0) && (CeilDiv(n, 32) * mt <= target); const bool square_ok = (n % 64 == 0); @@ -826,7 +876,7 @@ inline int SelectSwapABTile(int m, int n, int k, int target) { // The dense ladder; -1 when no tile supports the shape. inline int SelectBF16Cfg(int m, int n, int k, int sm_count) { - const int target = ResolveSmCount(sm_count); + const int target = sm_count > 0 ? sm_count : GetSmCount(); if (m >= 4096) { return SelectLargeMTile(m, n, k, target); } @@ -862,7 +912,7 @@ inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { if (m >= 128) { // M stays 128 (the 1-CTA MMA requires M == 128); step finer on N // only while the coarser tile underfills the grid. - const int target = ResolveSmCount(sm_count); + const int target = sm_count > 0 ? sm_count : GetSmCount(); auto tiles = [&](int tm, int tn) { return CeilDiv(m, tm) * CeilDiv(n, tn); }; @@ -909,7 +959,7 @@ inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, return kMaskPair256x256; } if (mm >= 128) { - const int target = ResolveSmCount(sm_count); + const int target = sm_count > 0 ? sm_count : GetSmCount(); auto tiles = [&](int tm, int tn) { return num_experts * CeilDiv(mm, tm) * CeilDiv(n, tn); }; @@ -955,100 +1005,21 @@ inline int SelectBF16BatchCfg(int m, int n, int k) { return -1; } -// ---- Tile tables as launcher policies -------------------------------------- - -struct DenseTiles { - static constexpr const auto& tiles = kBF16DenseTiles; -}; -struct ContiguousTiles { - static constexpr const auto& tiles = kBF16ContiguousTiles; -}; -struct MaskedTiles { - static constexpr const auto& tiles = kBF16MaskedTiles; -}; -struct BatchTiles { - static constexpr const auto& tiles = kBF16BatchTiles; -}; - -// Divisibility contract of a selected tile: the output M/N tile multiples -// (N relaxes to %64 for predicated tails and %32 for non-power-of-2 widths), -// K a KBlockK multiple. SwapAB swaps the roles: KBlockM tiles the weight -// (output N), KBlockN the activation (output M). -inline void CheckBF16TileShape(const char* what, const TileSpec& t, int m, - int n, int k) { - const int n_mod = - t.force_ntail ? 64 - : (((t.block_n & (t.block_n - 1)) != 0) ? 32 : t.block_n); - const int m_div = t.swap_ab ? t.block_n : t.block_m; - const int n_div = t.swap_ab ? t.block_m : n_mod; - TORCH_CHECK(m % m_div == 0, what, " requires M to be divisible by ", m_div, - ", got ", m); - TORCH_CHECK(n % n_div == 0, what, " requires N to be divisible by ", n_div, - ", got ", n); - TORCH_CHECK(k % t.block_k == 0, what, " requires K to be divisible by ", - t.block_k, ", got ", k); -} - -template -inline void LaunchSelected(int cfg, const char* what, int m_check, - GemmParams& params, int sm_count, - cudaStream_t stream) { - CheckBF16TileShape(what, Tiles::tiles[cfg], m_check, params.n, params.k); - const GemmShape shape = {.m = params.m, - .n = params.n, - .k = params.k, - .m_grid = params.m, - .sm_count = sm_count, - .has_bias = false}; - kTileLaunchers[cfg]( - params, shape, stream); -} - -// Selects, validates and launches. The .cu mode branches call these. -inline void LaunchDense(GemmParams& params, int sm_count, cudaStream_t stream) { - const int cfg = SelectBF16Cfg(params.m, params.n, params.k, sm_count); - TORCH_CHECK(cfg >= 0, "No BF16 dense GEMM tile supports M=", params.m, - ", N=", params.n, ", K=", params.k); - LaunchSelected( - cfg, "BF16 dense GEMM", params.m, params, sm_count, stream); -} - -inline void LaunchContiguous(GemmParams& params, int sm_count, - cudaStream_t stream) { - const int cfg = - SelectBF16ContiguousCfg(params.m, params.n, params.k, sm_count); - TORCH_CHECK(cfg >= 0, - "bf16 contiguous GEMM: unsupported shape M=", params.m, - " N=", params.n, " K=", params.k); - LaunchSelected( - cfg, "bf16 contiguous GEMM", params.m, params, sm_count, stream); -} - -inline void LaunchMasked(GemmParams& params, int sm_count, - cudaStream_t stream) { - const int cfg = - SelectBF16MaskedCfg(params.num_experts, params.max_m_per_expert, - params.n, params.k, sm_count); - TORCH_CHECK(cfg >= 0, - "bf16 masked GEMM: unsupported shape E=", params.num_experts, - " max_m_per_expert=", params.max_m_per_expert, " N=", params.n, - " K=", params.k); - LaunchSelected(cfg, "bf16 masked GEMM", - params.max_m_per_expert, - params, sm_count, stream); -} - -inline void LaunchBatch(GemmParams& params, int sm_count, cudaStream_t stream) { - const int cfg = - SelectBF16BatchCfg(params.max_m_per_expert, params.n, params.k); - TORCH_CHECK( - cfg >= 0, "bf16 batch GEMM: unsupported shape B=", params.num_experts, - " M=", params.max_m_per_expert, " N=", params.n, " K=", params.k, - ". Need one of: (M%256==0 && N%256==0), " - "(M%128==0 && N%256==0), or (M%64==0 && N%128==0)."); - LaunchSelected(cfg, "bf16 batch GEMM", - params.max_m_per_expert, - params, sm_count, stream); +// BF16 picks from the rule ladder above, one table per mode. +inline int PickBf16Tile(KernelMode mode, const GemmShape& shape) { + switch (mode) { + case KernelMode::Dense: + return SelectBF16Cfg(shape.m, shape.n, shape.k, shape.sm_count); + case KernelMode::Contiguous: + return SelectBF16ContiguousCfg(shape.m, shape.n, shape.k, + shape.sm_count); + case KernelMode::Masked: + return SelectBF16MaskedCfg(shape.m_grid / shape.m, shape.m, shape.n, + shape.k, shape.sm_count); + case KernelMode::Batch: + return SelectBF16BatchCfg(shape.m, shape.n, shape.k); + } + return -1; } } // namespace bf16 diff --git a/csrc/kernel/gemm/gemm_kernel.cuh b/csrc/kernel/gemm/gemm_kernel.cuh index 77df8a7..fdba905 100644 --- a/csrc/kernel/gemm/gemm_kernel.cuh +++ b/csrc/kernel/gemm/gemm_kernel.cuh @@ -518,7 +518,7 @@ void gemm_impl_body(GemmParams& params, const int sm_count, using ClusterShape_MNK = typename KernelTraits::ClusterShape_MNK; static constexpr int KCTAsPerCluster = cute::size(ClusterShape_MNK{}); // Same SM-count resolution as the dispatch-site tile heuristics. - const int raw_sm_count = ResolveSmCount(sm_count); + const int raw_sm_count = sm_count > 0 ? sm_count : GetSmCount(); // Round down to a multiple of KCTAsPerCluster. const int runtime_sm_count = (raw_sm_count / KCTAsPerCluster) * KCTAsPerCluster; diff --git a/csrc/kernel/gemm/gemm_utils.h b/csrc/kernel/gemm/gemm_utils.h index 453a870..30d1c58 100644 --- a/csrc/kernel/gemm/gemm_utils.h +++ b/csrc/kernel/gemm/gemm_utils.h @@ -64,21 +64,4 @@ inline void CheckDivisible(int64_t value, int64_t divisor, const char* name) { ", got ", value); } -// SM count for the tile-selection heuristics; sm_count <= 0 falls back to the -// cached device count so dispatch matches what gemm_impl launches on. -inline int ResolveSmCount(int sm_count) { - return sm_count > 0 ? sm_count : GetSmCount(); -} - -inline void CheckGemmTileShape(int64_t m, int64_t n, int64_t k, int64_t tile_m, - int64_t tile_n, int64_t tile_k, - const char* kernel_name) { - TORCH_CHECK(m % tile_m == 0, kernel_name, " requires M to be divisible by ", - tile_m, ", got ", m); - TORCH_CHECK(n % tile_n == 0, kernel_name, " requires N to be divisible by ", - tile_n, ", got ", n); - TORCH_CHECK(k % tile_k == 0, kernel_name, " requires K to be divisible by ", - tile_k, ", got ", k); -} - } // namespace halops diff --git a/csrc/kernel/gemm/group_contiguous_gemm.cu b/csrc/kernel/gemm/group_contiguous_gemm.cu index 28adc27..99e314d 100644 --- a/csrc/kernel/gemm/group_contiguous_gemm.cu +++ b/csrc/kernel/gemm/group_contiguous_gemm.cu @@ -66,8 +66,7 @@ void GroupContiguousGemm(const torch::Tensor& input, params.use_pdl = true; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored; dispatch and launch - // live in gemm_dispatch.cuh (bf16::LaunchContiguous). + // Native BF16: sfa/sfb/bias/alpha are ignored. const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -84,7 +83,15 @@ void GroupContiguousGemm(const torch::Tensor& input, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - bf16::LaunchContiguous(params, sm, stream); + LaunchCfg( + params, + {.m = m, + .n = n, + .k = k, + .m_grid = m, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 contiguous grouped GEMM requires sfa/sfb " diff --git a/csrc/kernel/gemm/group_masked_gemm.cu b/csrc/kernel/gemm/group_masked_gemm.cu index b934823..8db2ac1 100644 --- a/csrc/kernel/gemm/group_masked_gemm.cu +++ b/csrc/kernel/gemm/group_masked_gemm.cu @@ -75,8 +75,7 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.use_pdl = true; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored; dispatch and launch - // live in gemm_dispatch.cuh (bf16::LaunchMasked). + // Native BF16: sfa/sfb/bias/alpha are ignored. const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -93,7 +92,15 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - bf16::LaunchMasked(params, sm, stream); + LaunchCfg( + params, + {.m = max_m_per_expert, + .n = n, + .k = k, + .m_grid = m, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 masked grouped GEMM requires sfa/sfb scale " From db2f0be308d7b31c01e16bf8f51fe31735413e0c Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 19 Nov 2026 15:58:59 +0800 Subject: [PATCH 09/14] refactor(gemm): merge the BF16 mode tables into one candidate table With one tile table per mode, mapping a kind to its candidates needed its own adapter and the same tile was listed in up to four tables. - kBF16DenseTiles / kBF16ContiguousTiles / kBF16MaskedTiles / kBF16BatchTiles collapse into kBF16Tiles: 40 list entries become 28 distinct tiles. - The four id enums take their values from Bf16TileId(), a consteval lookup in that table, so an id cannot point at the wrong tile and a tile missing from the table fails to compile instead of selecting -1 at run time. - CandidateTiles replaces the CandidateTilesFor adapter: every kind now resolves its candidates through the same single layer, and LaunchCfg / kTileLaunchers go back to CandidateTiles. - The selection rules are untouched. PickBf16Tile still dispatches to the dense / contiguous / masked / batch ladders; the modes differ in how they pick, not in which table the ids index. Verified: build clean; the four GEMM test files pass (183 passed, 2 xfailed); ci/test_benchmark.py passes all eight configs within the 5% threshold. Co-Authored-By: Claude Code --- csrc/kernel/gemm/gemm_dispatch.cuh | 138 +++++++++++++---------------- csrc/kernel/gemm/gemm_tile.cuh | 80 ++++++++--------- 2 files changed, 99 insertions(+), 119 deletions(-) diff --git a/csrc/kernel/gemm/gemm_dispatch.cuh b/csrc/kernel/gemm/gemm_dispatch.cuh index 4a96a01..cea77a7 100644 --- a/csrc/kernel/gemm/gemm_dispatch.cuh +++ b/csrc/kernel/gemm/gemm_dispatch.cuh @@ -357,29 +357,8 @@ inline int PickTile(const TileSpec* tiles, int count, MmaKind kind, // Dispatch using TileLauncher = void (*)(GemmParams&, const GemmShape&, cudaStream_t); -// Candidates is any type exposing `static constexpr tiles`. Every kind draws -// from one table; BF16 has a separate one per mode. -template -struct CandidateTilesFor { - static constexpr const auto& tiles = CandidateTiles::tiles; -}; -template <> -struct CandidateTilesFor { - static constexpr const auto& tiles = kBF16DenseTiles; -}; -template <> -struct CandidateTilesFor { - static constexpr const auto& tiles = kBF16ContiguousTiles; -}; -template <> -struct CandidateTilesFor { - static constexpr const auto& tiles = kBF16MaskedTiles; -}; -template <> -struct CandidateTilesFor { - static constexpr const auto& tiles = kBF16BatchTiles; -}; - +// Candidates is any type exposing `static constexpr tiles`; every kind +// resolves through CandidateTiles (gemm_tile.cuh). // Divisibility contract of a selected tile: the output M/N tile multiples // (N relaxes to %64 for predicated tails and %32 for non-power-of-2 widths), // K a KBlockK multiple. SwapAB swaps the roles: KBlockM tiles the weight @@ -431,7 +410,7 @@ constexpr std::array MakeTileLaunchers( } template > + class Candidates = CandidateTiles> inline constexpr auto kTileLaunchers = MakeTileLaunchers( std::make_index_sequence{}); @@ -450,7 +429,7 @@ int PickBf16Tile(KernelMode mode, const GemmShape& shape); template void LaunchCfg(GemmParams& params, GemmShape shape, cudaStream_t stream) { shape.op = Op; - constexpr auto& candidates = CandidateTilesFor::tiles; + constexpr auto& candidates = CandidateTiles::tiles; const int pick = Kind == MmaKind::BF16 ? bf16::PickBf16Tile(Mode, shape) @@ -585,36 +564,37 @@ inline SmallNTile PickSmallNTile(int m, int n, int64_t target) { } // ---- Dense ----------------------------------------------------------------- -// Ids into kBF16DenseTiles (gemm_tile.cuh); the enum order mirrors the table. +// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum DenseTile : int { - kPair256x256, // 256x256 pair, 6 stages - kPair256x256P7, - kPair256x128, // 8 stages - kPair256x128Ntail, - kPair256x128P9, - kPair256x128P9Ntail, - kPair256x192, - kPair256x64, // 10 stages - kM128x256, - kM128x128, - kM128x64, // 8 stages - kM128x32, // 10 stages - kPair128x64P18, // 18 stages, 1 epilogue warp group - kM64x128, - kM64x96P11, // 11 stages, 1 epilogue warp group - kM64x224, // 1 epilogue warp group - kM64x64, // 2 epilogue warp groups, 10 stages - kM64x64_1wg, - kM64x64_1wgP14, - kM64x32_1wg, - kM64x32_1wgP18, - kSwap128x64, - kSwap128x32, - kSwap256x64Pair, - kSwap128x64K128, // SwapAB, KBlockK=128 (k >= 8192) + kPair256x256 = Bf16TileId(kBF16_256x256_pair), + kPair256x256P7 = Bf16TileId(kBF16_256x256_pair_p7), + kPair256x128 = Bf16TileId(kBF16_256x128_pair), + kPair256x128Ntail = Bf16TileId(kBF16_256x128_pair_ntail), + kPair256x128P9 = Bf16TileId(kBF16_256x128_pair_p9), + kPair256x128P9Ntail = Bf16TileId(kBF16_256x128_pair_p9_ntail), + kPair256x192 = Bf16TileId(kBF16_256x192_pair), + kPair256x64 = Bf16TileId(kBF16_256x64_pair), + kM128x256 = Bf16TileId(kBF16_128x256), + kM128x128 = Bf16TileId(kBF16_128x128), + kM128x64 = Bf16TileId(kBF16_128x64), + kM128x32 = Bf16TileId(kBF16_128x32), + kPair128x64P18 = Bf16TileId(kBF16_128x64_pair_p18), + kM64x128 = Bf16TileId(kBF16_64x128), + kM64x96P11 = Bf16TileId(kBF16_64x96_p11), + kM64x224 = Bf16TileId(kBF16_64x224), + kM64x64 = Bf16TileId(kBF16_64x64), + kM64x64_1wg = Bf16TileId(kBF16_64x64_1wg), + kM64x64_1wgP14 = Bf16TileId(kBF16_64x64_1wg_p14), + kM64x32_1wg = Bf16TileId(kBF16_64x32_1wg), + kM64x32_1wgP18 = Bf16TileId(kBF16_64x32_1wg_p18), + kSwap128x64 = Bf16TileId(kBF16_128x64_swap), + kSwap128x32 = Bf16TileId(kBF16_128x32_swap), + kSwap256x64Pair = Bf16TileId(kBF16_256x64_swap_pair), + kSwap128x64K128 = Bf16TileId(kBF16_128x64x128_swap), }; -static_assert(kSwap128x64K128 + 1 == static_cast(kBF16DenseTiles.size()), - "BF16 dense tile table and DenseTile enum drifted apart"); +static_assert(kSwap128x64K128 >= 0 && + kSwap128x64K128 < static_cast(kBF16Tiles.size()), + "BF16 dense tile id outside kBF16Tiles"); // m >= 4096: pair tiles, with a small-N ladder for narrow N. inline int SelectLargeMTile(int m, int n, int k, int target) { @@ -891,18 +871,18 @@ inline int SelectBF16Cfg(int m, int n, int k, int sm_count) { // ---- Grouped / batch ------------------------------------------------------- -// Ids into kBF16ContiguousTiles (gemm_tile.cuh). +// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum ContiguousTile : int { - kContPair256x256, // 256x256 pair, 7 stages - kContPair256x128, // 256x128 pair, 9 stages - kContM128x256, // 128x256, 16 overlap cols - kContM128x128, // 128x128, 6 stages - kContM128x64, // 128x64, 16 overlap cols - kContSwap128x64, + kContPair256x256 = Bf16TileId(kBF16_256x256_pair_p7), + kContPair256x128 = Bf16TileId(kBF16_256x128_pair_p9), + kContM128x256 = Bf16TileId(kBF16_128x256_ovlp16), + kContM128x128 = Bf16TileId(kBF16_128x128_p6), + kContM128x64 = Bf16TileId(kBF16_128x64_ovlp16), + kContSwap128x64 = Bf16TileId(kBF16_128x64_swap), }; -static_assert(kContSwap128x64 + 1 == - static_cast(kBF16ContiguousTiles.size()), - "BF16 contiguous tile table and enum drifted apart"); +static_assert(kContSwap128x64 >= 0 && + kContSwap128x64 < static_cast(kBF16Tiles.size()), + "BF16 contiguous tile id outside kBF16Tiles"); // m is the total token count. inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { @@ -939,17 +919,18 @@ inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { return kContSwap128x64; } -// Ids into kBF16MaskedTiles (gemm_tile.cuh). +// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum MaskedTile : int { - kMaskM128x256, // 128x256, 16 overlap cols - kMaskSwap128x64, - kMaskM128x128, // 128x128, 6 stages - kMaskM128x64, // 128x64, 16 overlap cols - kMaskPair256x256, // 256x256 pair, 7 stages - kMaskPair256x128, // 256x128 pair, 9 stages + kMaskM128x256 = Bf16TileId(kBF16_128x256_ovlp16), + kMaskSwap128x64 = Bf16TileId(kBF16_128x64_swap), + kMaskM128x128 = Bf16TileId(kBF16_128x128_p6), + kMaskM128x64 = Bf16TileId(kBF16_128x64_ovlp16), + kMaskPair256x256 = Bf16TileId(kBF16_256x256_pair_p7), + kMaskPair256x128 = Bf16TileId(kBF16_256x128_pair_p9), }; -static_assert(kMaskPair256x128 + 1 == static_cast(kBF16MaskedTiles.size()), - "BF16 masked tile table and enum drifted apart"); +static_assert(kMaskPair256x128 >= 0 && + kMaskPair256x128 < static_cast(kBF16Tiles.size()), + "BF16 masked tile id outside kBF16Tiles"); // Masked pads every expert to max_m_per_expert, so the grid scales with // num_experts * ceil(max_m / tm) * ceil(n / tn). @@ -982,14 +963,15 @@ inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, return kMaskSwap128x64; } -// Ids into kBF16BatchTiles (gemm_tile.cuh). +// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum BatchTile : int { - kBatchPair256x256, // 256x256 pair, 6 stages - kBatchM128x256, // 128x256, 16 overlap cols - kBatchSwap128x64, + kBatchPair256x256 = Bf16TileId(kBF16_256x256_pair), + kBatchM128x256 = Bf16TileId(kBF16_128x256_ovlp16), + kBatchSwap128x64 = Bf16TileId(kBF16_128x64_swap), }; -static_assert(kBatchSwap128x64 + 1 == static_cast(kBF16BatchTiles.size()), - "BF16 batch tile table and enum drifted apart"); +static_assert(kBatchSwap128x64 >= 0 && + kBatchSwap128x64 < static_cast(kBF16Tiles.size()), + "BF16 batch tile id outside kBF16Tiles"); // Pure alignment ladder (no runtime SM reasoning); m is one item's rows. inline int SelectBF16BatchCfg(int m, int n, int k) { diff --git a/csrc/kernel/gemm/gemm_tile.cuh b/csrc/kernel/gemm/gemm_tile.cuh index b5bc3b4..2d95593 100644 --- a/csrc/kernel/gemm/gemm_tile.cuh +++ b/csrc/kernel/gemm/gemm_tile.cuh @@ -16,6 +16,7 @@ #include #include +#include #include #include "common/mx_quant.cuh" @@ -479,11 +480,10 @@ struct CandidateTiles { // can mirror the FP8 configs. epi_warp_groups=1 marks the 1-epilogue-warp- // group layouts (narrow tiles, 2SM "2x2" TMEM layout); force_ntail marks the // predicated N-tail store (N only has to divide 64, or 32 for non-power-of-2 -// widths). dense_only stays false on every BF16 tile: each mode picks from -// its own table below, so the flag is never consulted. +// widths). dense_only stays false on every BF16 tile: the mode selectors in +// gemm_dispatch.cuh pick the tile, so the flag is never consulted. // -// Dense table. Order defines the id the dense selector returns -// (SelectBF16Cfg in gemm_dispatch.cuh); keep the two in sync. +// One tile table serves all four modes; ids are derived from it below. // --------------------------------------------------------------------------- constexpr TileSpec kBF16_256x256_pair = {.block_m = 256, .block_n = 256, @@ -597,22 +597,6 @@ constexpr TileSpec kBF16_128x64x128_swap = {.block_m = 128, .main_stages = 4, .swap_ab = true}; -inline constexpr std::array kBF16DenseTiles = { - kBF16_256x256_pair, kBF16_256x256_pair_p7, - kBF16_256x128_pair, kBF16_256x128_pair_ntail, - kBF16_256x128_pair_p9, kBF16_256x128_pair_p9_ntail, - kBF16_256x192_pair, kBF16_256x64_pair, - kBF16_128x256, kBF16_128x128, - kBF16_128x64, kBF16_128x32, - kBF16_128x64_pair_p18, kBF16_64x128, - kBF16_64x96_p11, kBF16_64x224, - kBF16_64x64, kBF16_64x64_1wg, - kBF16_64x64_1wg_p14, kBF16_64x32_1wg, - kBF16_64x32_1wg_p18, kBF16_128x64_swap, - kBF16_128x32_swap, kBF16_256x64_swap_pair, - kBF16_128x64x128_swap, -}; - // Grouped/batch tiles: deeper / TMEM-overlapped variants of the dense shapes. constexpr TileSpec kBF16_128x256_ovlp16 = {.block_m = 128, .block_n = 256, @@ -627,31 +611,45 @@ constexpr TileSpec kBF16_128x64_ovlp16 = {.block_m = 128, .main_stages = 8, .tmem_overlap = 16}; -// Order defines the id the per-mode selectors return (gemm_dispatch.cuh). -inline constexpr std::array kBF16ContiguousTiles = { - kBF16_256x256_pair_p7, // 0 - kBF16_256x128_pair_p9, // 1 - kBF16_128x256_ovlp16, // 2 - kBF16_128x128_p6, // 3 - kBF16_128x64_ovlp16, // 4 - kBF16_128x64_swap, // 5 +// Every BF16 launch draws from this one table; the per-mode ids in +// gemm_dispatch.cuh index it directly, so a tile several modes share appears +// once. Order is free apart from keeping the dense block first, which is what +// the historical id order was. +inline constexpr std::array kBF16Tiles = { + kBF16_256x256_pair, kBF16_256x256_pair_p7, + kBF16_256x128_pair, kBF16_256x128_pair_ntail, + kBF16_256x128_pair_p9, kBF16_256x128_pair_p9_ntail, + kBF16_256x192_pair, kBF16_256x64_pair, + kBF16_128x256, kBF16_128x128, + kBF16_128x64, kBF16_128x32, + kBF16_128x64_pair_p18, kBF16_64x128, + kBF16_64x96_p11, kBF16_64x224, + kBF16_64x64, kBF16_64x64_1wg, + kBF16_64x64_1wg_p14, kBF16_64x32_1wg, + kBF16_64x32_1wg_p18, kBF16_128x64_swap, + kBF16_128x32_swap, kBF16_256x64_swap_pair, + kBF16_128x64x128_swap, + // Grouped/batch: deeper or TMEM-overlapped variants of the dense shapes. + kBF16_128x256_ovlp16, kBF16_128x128_p6, + kBF16_128x64_ovlp16, }; -inline constexpr std::array kBF16MaskedTiles = { - kBF16_128x256_ovlp16, // 0 - kBF16_128x64_swap, // 1 - kBF16_128x128_p6, // 2 - kBF16_128x64_ovlp16, // 3 - kBF16_256x256_pair_p7, // 4 - kBF16_256x128_pair_p9, // 5 -}; +// Index of a tile in kBF16Tiles. The per-mode ids in gemm_dispatch.cuh are +// derived from it, so an id cannot point at the wrong tile and a tile missing +// from the table fails to compile. +consteval int Bf16TileId(const TileSpec& t) { + for (std::size_t i = 0; i < kBF16Tiles.size(); ++i) { + if (kBF16Tiles[i] == t) { + return static_cast(i); + } + } + throw "BF16 tile missing from kBF16Tiles"; +} -inline constexpr std::array kBF16BatchTiles = { - kBF16_256x256_pair, // 0 - kBF16_128x256_ovlp16, // 1 - kBF16_128x64_swap, // 2 +template <> +struct CandidateTiles { + static constexpr const auto& tiles = kBF16Tiles; }; - // --------------------------------------------------------------------------- // Field-lock asserts: guard the designated-initializer tables above against // drift. These tables replaced hand-written GemmTile structs; the locks pin From bf02f0aa4c6c48d04d4dffedb0fbb9338943c794 Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Wed, 25 Nov 2026 21:08:51 +0800 Subject: [PATCH 10/14] refactor(gemm): fold the BF16 epilogue onto the shared store/overlap helpers First step of merging the BF16 epilogue into the shared one: epilogue_bf16 now reuses the helpers the quantized paths already have instead of keeping private copies. - D stores go through store_rows; the inline SwapAB b16 and predicated 256-bit copies are gone. Stores clip against the whole stacked D, not per batch: BF16 tiles never straddle a batch, and a per-batch bound kept the batch range live across the store loop (it spilled up to 104 bytes on the batch SwapAB tiles). - The overlap barrier uses overlap_arrive instead of a line-for-line copy. - d_shift computes the stacked-row to tile shift for both batch layouts ([M, B * N] and [B, M, N]); it replaces the BF16 path's own formula. - The EpiMIter loops always ran once (EpilogueTile and EpiComputeTile have the same M), so they are dropped and a static_assert pins the premise. Codegen against 7e512ad (cuobjdump --dump-resource-usage, 1238 gemm kernels): 1234 unchanged, including every quantized kernel; the two BF16 batch 128x256 kernels lose their 20 B spill, the two 128x32 SwapAB batch kernels go 160 -> 162 registers, no kernel spills. Verified: the four GEMM test files pass (183 passed, 2 xfailed); BF16 same-machine A/B against 7e512ad, two alternating rounds: dense_bf16 median -0.02% (-0.48%..+0.45%), batch_bf16 median -0.06% (-0.37%..+0.12%). ci/test_benchmark.py fails only dense_w8a8 8192x4096x4096 (+6.5..+7.6% over its 10-22 baseline), and 7e512ad fails it identically on this machine today, so that is drift of the stale baseline, not this change. Co-Authored-By: Claude Code --- csrc/kernel/gemm/epilogue.cuh | 261 ++++++++++++---------------------- 1 file changed, 91 insertions(+), 170 deletions(-) diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index eba88b4..076be9d 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -55,8 +55,9 @@ class CollectiveEpilogue { // Used by the BF16 epilogue path. using CopyOpT2R_Overlap = typename KernelTraits::CopyOpT2R_Overlap; using OverlapLoadTile = typename KernelTraits::OverlapLoadTile; - static constexpr uint32_t EpiMIter = - cute::size<0>(EpilogueTile{}) / cute::size<0>(EpiComputeTile{}); + // One epilogue compute tile spans the whole per-CTA M. + static_assert(cute::size<0>(EpilogueTile{}) == + cute::size<0>(EpiComputeTile{})); // Bias uses plain TMA (no 2SM multicast); each CTA loads its own copy. using CopyOpG2S_Bias = cute::SM90_TMA_LOAD; using CopyOpS2R = @@ -277,6 +278,20 @@ class CollectiveEpilogue { return 0; } } + // Shift from the stacked-row D pointer to the tile's D. The default Batch + // layout moves batch b's rows to row 0, columns b * N; [B, M, N] keeps + // the stacked row. + CUTLASS_DEVICE static int64_t d_shift( + Params const& p, TileScheduler const& scheduler, + TileRows const& rows) { + if constexpr (KernelTraits::KernelType == KernelMode::Batch) { + return p.batch_out_bmn ? 0 + : batch_col0(p, scheduler) - + (int64_t)rows.lo * p.d_ld; + } else { + return 0; + } + } CUTLASS_DEVICE static int64_t d_row(Params const& p, TileRows const& rows, int64_t row) { return (row - (int64_t)rows.lo) * p.d_ld; @@ -864,6 +879,11 @@ class CollectiveEpilogue { } }(); + // BF16 tiles never straddle a batch (the host requires whole tiles), + // so stores clip against the stacked D only; a per-batch bound would + // keep the batch range live across the store loop. + const TileRows store_bound{0, out_m, 0, out_m % KTileRows == 0}; + AccumulatorPipelineState acc_pipe_consumer_state; uint32_t epilogue_stage_idx = 0; @@ -880,15 +900,10 @@ class CollectiveEpilogue { (static_cast(partial_slot) * KNumCTA + cta_v) * KPartialM * KPartialN; } - // Batch: move the stacked row b * M + r to row r, columns b * N - // (already contiguous in the [B, M, N] layout). - int64_t row_shift = 0; - if constexpr (KernelTraits::KernelType == KernelMode::Batch) { - const int64_t b = - epilogue_params.batch_out_bmn ? 0 : scheduler.expert_idx(); - row_shift = b * static_cast(out_n) - - b * scheduler.max_m_per_expert() * d_ld; - } + const uint32_t block_m_idx = m_idx * KNumCTA + cta_v; + const TileRows rows = + tile_rows(scheduler, out_m, block_m_idx, n_idx); + const int64_t row_shift = d_shift(epilogue_params, scheduler, rows); float alpha_val = 1.0f; if constexpr (HasAlpha) { alpha_val = shared_storage.alpha[scheduler.expert_idx()]; @@ -896,10 +911,10 @@ class CollectiveEpilogue { acc_pipeline.consumer_wait(acc_pipe_consumer_state); epilogue_stage_idx = acc_pipe_consumer_state.index(); - auto t2r_sub = [&](uint32_t epi_m_idx, uint32_t sub_n_idx) { + auto t2r_sub = [&](uint32_t sub_n_idx) { cute::copy( tiled_t2r_sub, - thr_tacc_src_sub(cute::_, cute::_, cute::_, epi_m_idx, + thr_tacc_src_sub(cute::_, cute::_, cute::_, cute::_0{}, sub_n_idx, epilogue_stage_idx), thr_racc_dst_sub); if constexpr (!KernelTraits::SkipTmemFence) { @@ -907,7 +922,7 @@ class CollectiveEpilogue { } }; - auto r2g_sub = [&](uint32_t epi_m_idx, uint32_t sub_n_idx) { + auto r2g_sub = [&](uint32_t sub_n_idx) { // N-overhang predicate: a KBlockN that does not divide n // overhangs on the last tile, and D is stored register -> GMEM // (not TMA), so nothing clips OOB writes. The host enforces @@ -935,7 +950,6 @@ class CollectiveEpilogue { } } - const uint32_t block_m_idx = m_idx * KNumCTA + cta_v; auto dst_cur = cute::make_tensor(dst_sub.data() + row_shift, dst_sub.layout())( (cute::_, cute::_), cute::_, cute::_, cute::Int<0>{}, @@ -964,52 +978,11 @@ class CollectiveEpilogue { dst_arr = Converter::convert(src_arr); } - if constexpr (SwapAB) { - auto store_one = [&](uint32_t v_id) { - auto* addr = (TypeD*)&dst_cur(v_id); - auto val = src_sub[v_id]; - asm volatile("st.global.L1::no_allocate.b16 [%0], %1;" - : - : "l"(addr), "h"(*(uint16_t*)&val)); - }; - if (out_m % KernelTraits::KBlockN == 0) { - // Full M tiles: no bounds check needed. - CUTLASS_PRAGMA_UNROLL - for (uint32_t v_id = 0; v_id < src_sub.size(); ++v_id) { - store_one(v_id); - } - } else { - // Partial last M tile: skip rows past M. - CUTLASS_PRAGMA_UNROLL - for (uint32_t v_id = 0; v_id < src_sub.size(); ++v_id) { - if ((size_t)cute::get<1>(coord_cur(v_id)) >= - out_m) { - continue; - } - store_one(v_id); - } - } - } else { - if (out_m % KernelTraits::KBlockM == 0) { - // Full M tiles: no bounds check needed. - cute::copy(tiled_r2g_sub, src_sub, dst_cur); - } else { - // Predicate per store vector (one vector spans one M - // row), which keeps the 256-bit store. - auto pred_cur = - cute::make_tensor(cute::shape(src_sub)); - CUTLASS_PRAGMA_UNROLL - for (uint32_t v_id = 0; v_id < src_sub.size(); ++v_id) { - pred_cur(v_id) = - (size_t)cute::get<0>(coord_cur(v_id)) < out_m; - } - cute::copy_if(tiled_r2g_sub, pred_cur, src_sub, - dst_cur); - } - } + store_rows(tiled_r2g_sub, src_sub, dst_cur, coord_cur, + store_bound); }; - auto process_sub = [&](uint32_t epi_m_idx, uint32_t sub_n_idx) { + auto process_sub = [&](uint32_t sub_n_idx) { if constexpr (KernelTraits::IsSfbUnaligned) { // The last N tile overhangs N; a sub-tile is all in or all // out because N is a multiple of the sub-tile width. @@ -1019,8 +992,8 @@ class CollectiveEpilogue { return; } } - t2r_sub(epi_m_idx, sub_n_idx); - r2g_sub(epi_m_idx, sub_n_idx); + t2r_sub(sub_n_idx); + r2g_sub(sub_n_idx); }; if constexpr (KernelTraits::KTmemOverlapCols > 0) { @@ -1034,44 +1007,14 @@ class CollectiveEpilogue { uint32_t wg_sub_base = warp_group_idx * SubTilesPerWG; - auto overlap_barrier_arrive = [&]() { - constexpr int overlap_bar_threads = 4 * 32 + 32; - if constexpr (KNumCTA == 1) { - cutlass::arch::NamedBarrier::arrive(overlap_bar_threads, - 0); - } else { - if (cta_v == 0) { - cutlass::arch::NamedBarrier::arrive( - overlap_bar_threads, 0); - } else { - constexpr int wg_threads = 4 * 32; - cutlass::arch::NamedBarrier wg_barrier( - wg_threads, 1 /*barrier id*/); - wg_barrier.arrive_and_wait(); - if (threadIdx.x == warp_group_idx * 128) { - // The pair's MMA leader: V is the low bits of - // the cluster rank. - cutlass::arch::ClusterBarrier::arrive( - &shared_storage.overlap_cluster_bar, - cute::block_rank_in_cluster() - cta_v, - true /*pred*/); - } - } - } - }; - // Remaining (non-overlap) sub-tiles of the overlap WG. auto process_non_overlap_subs = [&]() { CUTLASS_PRAGMA_UNROLL - for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; - epi_m_idx++) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t s = 0; s < SubTilesPerWG; s++) { - uint32_t sub_idx = wg_sub_base + s; - if (sub_idx < ovlp_sub_base || - sub_idx >= ovlp_sub_base + OverlapSubCount) { - process_sub(epi_m_idx, sub_idx); - } + for (uint32_t s = 0; s < SubTilesPerWG; s++) { + uint32_t sub_idx = wg_sub_base + s; + if (sub_idx < ovlp_sub_base || + sub_idx >= ovlp_sub_base + OverlapSubCount) { + process_sub(sub_idx); } } }; @@ -1128,72 +1071,62 @@ class CollectiveEpilogue { : 0; if (warp_group_idx == overlap_wg) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; - epi_m_idx++) { - cute::copy(tiled_t2r_ovlp, - thr_tacc_src_ovlp( - cute::_, cute::_, cute::_, epi_m_idx, - ovlp_wide_idx, epilogue_stage_idx), - thr_racc_dst_ovlp); - cutlass::arch::fence_view_async_tmem_load(); - } + cute::copy(tiled_t2r_ovlp, + thr_tacc_src_ovlp( + cute::_, cute::_, cute::_, cute::_0{}, + ovlp_wide_idx, epilogue_stage_idx), + thr_racc_dst_ovlp); + cutlass::arch::fence_view_async_tmem_load(); } // Overlap columns read; MMA may proceed. if (warp_group_idx == overlap_wg) { - overlap_barrier_arrive(); + overlap_arrive(shared_storage, cta_v, warp_group_idx); } if (warp_group_idx == overlap_wg) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; - epi_m_idx++) { - { - constexpr int kN = - decltype(cute::size(thr_rd_ovlp))::value; - using Converter = - cutlass::NumericArrayConverter< - TypeD, TypeAccumulate, kN>; - auto& src_arr = reinterpret_cast< - cutlass::Array const&>( - *thr_racc_dst_ovlp.data()); - auto& dst_arr = reinterpret_cast< - cutlass::Array&>( - *thr_rd_ovlp.data()); - if constexpr (HasAlpha) { - CUTLASS_PRAGMA_UNROLL - for (int i = 0; i < kN; ++i) { - src_arr[i] *= alpha_val; - } + { + constexpr int kN = + decltype(cute::size(thr_rd_ovlp))::value; + using Converter = + cutlass::NumericArrayConverter< + TypeD, TypeAccumulate, kN>; + auto& src_arr = reinterpret_cast< + cutlass::Array const&>( + *thr_racc_dst_ovlp.data()); + auto& dst_arr = reinterpret_cast< + cutlass::Array&>( + *thr_rd_ovlp.data()); + if constexpr (HasAlpha) { + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < kN; ++i) { + src_arr[i] *= alpha_val; } - dst_arr = Converter::convert(src_arr); } + dst_arr = Converter::convert(src_arr); + } - const uint32_t block_m_idx = - m_idx * KNumCTA + cta_v; - auto dst_cur = cute::make_tensor( - dst_ovlp.data() + row_shift, - dst_ovlp.layout())((cute::_, cute::_), cute::_, - cute::_, cute::Int<0>{}, - ovlp_wide_idx, block_m_idx, - n_idx); + auto dst_cur = cute::make_tensor( + dst_ovlp.data() + row_shift, + dst_ovlp.layout())((cute::_, cute::_), cute::_, + cute::_, cute::Int<0>{}, + ovlp_wide_idx, block_m_idx, + n_idx); - if constexpr (SwapAB) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t v_id = 0; v_id < src_ovlp.size(); - ++v_id) { - auto* addr = (TypeD*)&dst_cur(v_id); - auto val = src_ovlp[v_id]; - asm volatile( - "st.global.L1::no_allocate.b16 " - "[%0], %1;" - : - : "l"(addr), "h"(*(uint16_t*)&val)); - } - } else { - cute::copy(tiled_r2g_ovlp, src_ovlp, dst_cur); + if constexpr (SwapAB) { + CUTLASS_PRAGMA_UNROLL + for (uint32_t v_id = 0; v_id < src_ovlp.size(); + ++v_id) { + auto* addr = (TypeD*)&dst_cur(v_id); + auto val = src_ovlp[v_id]; + asm volatile( + "st.global.L1::no_allocate.b16 " + "[%0], %1;" + : + : "l"(addr), "h"(*(uint16_t*)&val)); } + } else { + cute::copy(tiled_r2g_ovlp, src_ovlp, dst_cur); } process_non_overlap_subs(); @@ -1203,17 +1136,13 @@ class CollectiveEpilogue { // T2R + R2G per sub-tile, then arrive after the last read. if (warp_group_idx == overlap_wg) { CUTLASS_PRAGMA_UNROLL - for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; - epi_m_idx++) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t o = 0; o < OverlapSubCount; o++) { - process_sub(epi_m_idx, ovlp_sub_base + o); - } + for (uint32_t o = 0; o < OverlapSubCount; o++) { + process_sub(ovlp_sub_base + o); } } if (warp_group_idx == overlap_wg) { - overlap_barrier_arrive(); + overlap_arrive(shared_storage, cta_v, warp_group_idx); } if (warp_group_idx == overlap_wg) { @@ -1223,23 +1152,15 @@ class CollectiveEpilogue { if (warp_group_idx != overlap_wg) { CUTLASS_PRAGMA_UNROLL - for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; - epi_m_idx++) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t s = 0; s < SubTilesPerWG; s++) { - process_sub(epi_m_idx, wg_sub_base + s); - } + for (uint32_t s = 0; s < SubTilesPerWG; s++) { + process_sub(wg_sub_base + s); } } } else { + uint32_t wg_sub_base = warp_group_idx * SubTilesPerWG; CUTLASS_PRAGMA_UNROLL - for (uint32_t epi_m_idx = 0; epi_m_idx < EpiMIter; - epi_m_idx++) { - uint32_t wg_sub_base = warp_group_idx * SubTilesPerWG; - CUTLASS_PRAGMA_UNROLL - for (uint32_t s = 0; s < SubTilesPerWG; s++) { - process_sub(epi_m_idx, wg_sub_base + s); - } + for (uint32_t s = 0; s < SubTilesPerWG; s++) { + process_sub(wg_sub_base + s); } } From eaaea27cc885d56d8473817df51802b34ac77f9a Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 26 Nov 2026 03:04:18 +0800 Subject: [PATCH 11/14] refactor(gemm): run the BF16 epilogue through the shared R2G sub-tile loop epilogue_bf16 is gone: BF16 now takes the same sub-tile loop as the non-swap quantized path, and epilogue() dispatches between two families only (staged SwapAB quantized vs. the R2G loop). The BF16 differences are three compile-time switches in that loop: - Loader: BF16 reads TMEM through the partitioned tiled copy, which also covers the 16dp (64-row CTA) and 2SM "2x2" accumulator layouts; the quantized path keeps its raw unit load. - Store bound: BF16 clips against the whole stacked D (its tiles never straddle a batch), keeping the batch range out of the store loop. - Store target: a stream-K tail tile writes its fp32 partial; the BF16 N-tail joins the existing skip of sub-tiles past N. Overlap scheduling uses the shared run(): both BF16 overlap tiles overlap 16 columns, exactly one sub-tile, so the old wide-load branch read one sub-tile too. The traits that only fed that branch are removed (CopyOpT2R_Overlap, OverlapLoadTile, KOverlapLoadN, KWideTilesTotal, KSubTilesPerWG, KOverlapSubCount). d_shift reads batch_out_bmn for BF16 only, so the quantized shift is unchanged. Codegen against 7e512ad (1238 gemm kernels): every quantized kernel is unchanged. 24 BF16 kernels move; none uses LOCAL, but at the 168-register cap ptxas trades spills between tiles: dense 256x256 pair and contiguous 128x256 lose theirs (36/88 and 40/116 B), dense 128x256 and contiguous 256x256 pair gain 40/112 and 40/124 B. SASS shows what spills: the tile scheduler's start tile, grid stride, total tiles and warp_idx, which 7e512ad keeps in uniform registers, now sit in regular registers and are reloaded about five times per tile. Eight source-level variants of the new loop (in-place convert, bound selection, raw-register buffer, plain unit loop instead of run(), TMEM address, tile_rows, stream-K state) all leave it unchanged, and efa8a1b compiles the same tile without it, so it is ptxas's global uniform-register assignment, not one line of the loop. Verified: the four GEMM test files pass (183 passed, 2 xfailed), covering the BF16 overlap, N-tail, stream-K, SwapAB and batch-major cases. Same-machine A/B against 7e512ad, two alternating rounds: dense_bf16 median -0.27% (-1.50%..+0.30%; mid-M 256 and 1024 x4096x4096 -1.1%/-1.5%), batch_bf16 -0.03% (-0.26%..+0.17%), group_contiguous_bf16 +0.24% (-1.04%..+0.81%; the three M>=4096 4096-wide shapes on 256x256 pair +0.5..+0.8%), group_masked_bf16 -0.05% (-0.63%..+0.14%). Co-Authored-By: Claude Code --- csrc/kernel/gemm/epilogue.cuh | 559 ++++++----------------------- csrc/kernel/gemm/kernel_traits.cuh | 31 -- 2 files changed, 109 insertions(+), 481 deletions(-) diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index 076be9d..2671ea0 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -52,9 +52,6 @@ class CollectiveEpilogue { using CopyOpT2R = typename KernelTraits::CopyOpT2R; using CopyOpT2R_Sub = typename KernelTraits::CopyOpT2R_Sub; using OverlapComputeTile = typename KernelTraits::OverlapComputeTile; - // Used by the BF16 epilogue path. - using CopyOpT2R_Overlap = typename KernelTraits::CopyOpT2R_Overlap; - using OverlapLoadTile = typename KernelTraits::OverlapLoadTile; // One epilogue compute tile spans the whole per-CTA M. static_assert(cute::size<0>(EpilogueTile{}) == cute::size<0>(EpiComputeTile{})); @@ -285,9 +282,13 @@ class CollectiveEpilogue { Params const& p, TileScheduler const& scheduler, TileRows const& rows) { if constexpr (KernelTraits::KernelType == KernelMode::Batch) { - return p.batch_out_bmn ? 0 - : batch_col0(p, scheduler) - - (int64_t)rows.lo * p.d_ld; + const int64_t shift = + batch_col0(p, scheduler) - (int64_t)rows.lo * p.d_ld; + if constexpr (KernelTraits::KIsBF16) { + return p.batch_out_bmn ? 0 : shift; // only BF16 takes it + } else { + return shift; + } } else { return 0; } @@ -742,440 +743,6 @@ class CollectiveEpilogue { } } - template - CUTLASS_DEVICE void epilogue_bf16(Params const& epilogue_params, - AccumulatorPipeline& acc_pipeline, - SharedStorage& shared_storage, - TmemStorage& tmem_storage, int warp_idx, - TileScheduler& scheduler) { - int warp_group_idx = warp_idx / 4; - int block_rank_in_cluster = cute::block_rank_in_cluster(); - - cute::Layout cluster_layout_vmnk = - cute::tiled_divide(cute::make_layout(ClusterShape_MNK{}), - cute::make_tile(typename TiledMma::AtomThrID{})); - auto cta_coord_vmnk = - cluster_layout_vmnk.get_flat_coord(block_rank_in_cluster); - int cta_v = cute::get<0>(cta_coord_vmnk); - - cute::Tensor tmem_accumulators = tmem_storage.tmem_accumulators; - cute::Tensor acc = tmem_accumulators(cute::make_coord(cute::_, cute::_), - cute::_0{}, cute::_0{}, cute::_); - - // TMEM is read in 16-column sub-tiles; KOverlapSubCount of them at the - // stage boundary form the overlap region. - static constexpr int SubTilesPerWG = KernelTraits::KSubTilesPerWG; - static constexpr int OverlapSubCount = KernelTraits::KOverlapSubCount; - - cute::Tensor acc_sub_tile = - cute::flat_divide(acc, OverlapComputeTile{}); - - cute::TiledCopy tiled_t2r_sub = cute::make_tmem_copy( - CopyOpT2R_Sub{}, - acc_sub_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, cute::_0{})); - auto tx = threadIdx.x % cute::size(tiled_t2r_sub); - cute::ThrCopy thread_t2r_sub = tiled_t2r_sub.get_slice(tx); - - cute::Tensor thr_tacc_src_sub = - thread_t2r_sub.partition_S(acc_sub_tile); - cute::Tensor thr_demo_sub = thread_t2r_sub.partition_D( - acc_sub_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, cute::_0{})); - cute::Tensor thr_racc_dst_sub = - cute::make_tensor(cute::shape(thr_demo_sub)); - cute::Tensor thr_rd_sub = - cute::make_tensor(cute::shape(thr_demo_sub)); - - // Unswapped output dims. D rows are d_ld apart: N, or B * N for Batch, - // whose D is [M, B * N] with batch b in columns [b * N, (b + 1) * N). - const size_t out_m = epilogue_params.m; // activation M - const size_t out_n = epilogue_params.n; // weight N - const int64_t d_ld = epilogue_params.d_ld; - - cute::Tensor mD = [&]() { - if constexpr (SwapAB) { - auto stride_d = - cute::make_stride(cute::Int<1>{}, d_ld, out_m * out_n); - auto layout_d = - cute::make_layout(cute::make_shape(out_n, out_m, 1), - cute::append<3>(stride_d, cute::_0{})); - return cute::make_tensor( - cute::make_gmem_ptr(epilogue_params.ptr_d), layout_d); - } else { - auto stride_d = - cute::make_stride(d_ld, cute::_1{}, out_m * out_n); - auto layout_d = - cute::make_layout(cute::make_shape(out_m, out_n, 1), - cute::append<3>(stride_d, cute::_0{})); - return cute::make_tensor( - cute::make_gmem_ptr(epilogue_params.ptr_d), layout_d); - } - }(); - - cute::Tensor gD = cute::local_tile( - mD, cute::take<0, 2>(CtaShape_MNK{}), - cute::make_coord(cute::_, cute::_, cute::Int<0>{})); - - cute::Tensor gD_sub_tile = cute::flat_divide(gD, OverlapComputeTile{}); - auto tiled_r2g_sub = [&]() { - if constexpr (SwapAB) { - return cute::make_tiled_copy_D( - cute::Copy_Atom, TypeD>{}, - tiled_t2r_sub); - } else { - return cute::make_tiled_copy_D( - cute::Copy_Atom{}, - tiled_t2r_sub); - } - }(); - auto thr_r2g_sub = tiled_r2g_sub.get_slice(tx); - cute::Tensor src_sub = thr_r2g_sub.retile_S(thr_rd_sub); - cute::Tensor dst_sub = thr_r2g_sub.partition_D(gD_sub_tile); - - // Coordinates partitioned like dst: the stores below are not clipped, - // so the M bound is checked per element. - auto dst_coords_sub = [&]() { - auto mD_coords = cute::make_identity_tensor( - SwapAB ? cute::make_shape(out_n, out_m, 1) - : cute::make_shape(out_m, out_n, 1)); - auto gD_coords = cute::local_tile( - mD_coords, cute::take<0, 2>(CtaShape_MNK{}), - cute::make_coord(cute::_, cute::_, cute::Int<0>{})); - auto gD_sub_tile_coords = - cute::flat_divide(gD_coords, OverlapComputeTile{}); - return thr_r2g_sub.partition_D(gD_sub_tile_coords); - }(); - - // Stream-K: partials address a compact per-CTA [CtaShape_M][KBlockN] - // slot instead of the global D grid. - static constexpr int KPartialM = - cute::size<0>(cute::take<0, 2>(CtaShape_MNK{})); - static constexpr int KPartialN = - cute::size<1>(cute::take<0, 2>(CtaShape_MNK{})); - - // Built once against the workspace base (doing it in r2g_sub causes - // spills); same thread layout as the D store. Empty when !KStreamK. - auto partial_store = [&]() { - if constexpr (KStreamK) { - auto tiled_p = cute::make_tiled_copy_D( - cute::Copy_Atom< - cute::AutoVectorizingCopyWithAssumedAlignment<128>, - TypeAccumulate>{}, - tiled_t2r_sub); - auto thr_p = tiled_p.get_slice(tx); - return cute::make_tuple( - tiled_p, thr_p.retile_S(thr_racc_dst_sub), - thr_p.partition_D(cute::flat_divide( - cute::make_tensor( - cute::make_gmem_ptr(epilogue_params.ptr_partial), - cute::make_layout( - cute::make_shape(cute::Int{}, - cute::Int{}), - cute::make_stride(cute::Int{}, - cute::_1{}))), - OverlapComputeTile{}))); - } else { - return cute::make_tuple(); - } - }(); - - // BF16 tiles never straddle a batch (the host requires whole tiles), - // so stores clip against the stacked D only; a per-batch bound would - // keep the batch range live across the store loop. - const TileRows store_bound{0, out_m, 0, out_m % KTileRows == 0}; - - AccumulatorPipelineState acc_pipe_consumer_state; - - uint32_t epilogue_stage_idx = 0; - - while (scheduler.is_valid()) { - uint32_t m_idx = scheduler.m_idx(); - uint32_t n_idx = scheduler.n_idx(); - // Resolved per work item: < 0 stores the final bf16 result. - int partial_slot = -1; - int64_t partial_off = 0; - if constexpr (KStreamK) { - partial_slot = scheduler.partial_slot(); - partial_off = - (static_cast(partial_slot) * KNumCTA + cta_v) * - KPartialM * KPartialN; - } - const uint32_t block_m_idx = m_idx * KNumCTA + cta_v; - const TileRows rows = - tile_rows(scheduler, out_m, block_m_idx, n_idx); - const int64_t row_shift = d_shift(epilogue_params, scheduler, rows); - float alpha_val = 1.0f; - if constexpr (HasAlpha) { - alpha_val = shared_storage.alpha[scheduler.expert_idx()]; - } - acc_pipeline.consumer_wait(acc_pipe_consumer_state); - epilogue_stage_idx = acc_pipe_consumer_state.index(); - - auto t2r_sub = [&](uint32_t sub_n_idx) { - cute::copy( - tiled_t2r_sub, - thr_tacc_src_sub(cute::_, cute::_, cute::_, cute::_0{}, - sub_n_idx, epilogue_stage_idx), - thr_racc_dst_sub); - if constexpr (!KernelTraits::SkipTmemFence) { - cutlass::arch::fence_view_async_tmem_load(); - } - }; - - auto r2g_sub = [&](uint32_t sub_n_idx) { - // N-overhang predicate: a KBlockN that does not divide n - // overhangs on the last tile, and D is stored register -> GMEM - // (not TMA), so nothing clips OOB writes. The host enforces - // n % KSubTileN == 0, so one compare covers a whole sub-tile. - if constexpr (KernelTraits::KEpiNeedsNPredicate) { - const uint32_t sub_n_begin = - n_idx * static_cast(KernelTraits::KBlockN) + - sub_n_idx * - static_cast(KernelTraits::KSubTileN); - if (sub_n_begin >= static_cast(out_n)) { - return; - } - } - // Stream-K tail chunk: store the raw fp32 accumulator; the - // reduce kernel sums and casts. Stream-K is no-alpha only. - if constexpr (KStreamK) { - if (partial_slot >= 0) { - auto dst_p = cute::get<2>(partial_store); - dst_p.data() = dst_p.data() + partial_off; - copy(cute::get<0>(partial_store), - cute::get<1>(partial_store), - dst_p((cute::_, cute::_), cute::_, cute::_, - cute::Int<0>{}, sub_n_idx)); - return; - } - } - - auto dst_cur = cute::make_tensor(dst_sub.data() + row_shift, - dst_sub.layout())( - (cute::_, cute::_), cute::_, cute::_, cute::Int<0>{}, - sub_n_idx, block_m_idx, n_idx); - auto coord_cur = dst_coords_sub((cute::_, cute::_), cute::_, - cute::_, cute::Int<0>{}, - sub_n_idx, block_m_idx, n_idx); - - { - constexpr int kN = decltype(cute::size(thr_rd_sub))::value; - using Converter = - cutlass::NumericArrayConverter; - auto& src_arr = - reinterpret_cast&>( - *thr_racc_dst_sub.data()); - auto& dst_arr = - reinterpret_cast&>( - *thr_rd_sub.data()); - if constexpr (HasAlpha) { - CUTLASS_PRAGMA_UNROLL - for (int i = 0; i < kN; ++i) { - src_arr[i] *= alpha_val; - } - } - dst_arr = Converter::convert(src_arr); - } - - store_rows(tiled_r2g_sub, src_sub, dst_cur, coord_cur, - store_bound); - }; - - auto process_sub = [&](uint32_t sub_n_idx) { - if constexpr (KernelTraits::IsSfbUnaligned) { - // The last N tile overhangs N; a sub-tile is all in or all - // out because N is a multiple of the sub-tile width. - if (n_idx * cute::size<1>(TileShape{}) + - sub_n_idx * KernelTraits::KSubTileN >= - out_n) { - return; - } - } - t2r_sub(sub_n_idx); - r2g_sub(sub_n_idx); - }; - - if constexpr (KernelTraits::KTmemOverlapCols > 0) { - // Overlap WG alternates: wg1 on even stages, wg0 on odd. - uint32_t overlap_wg = 1 - (epilogue_stage_idx % 2); - - uint32_t ovlp_sub_base = - (epilogue_stage_idx % 2 == 0) - ? (2 * SubTilesPerWG - OverlapSubCount) - : 0; - - uint32_t wg_sub_base = warp_group_idx * SubTilesPerWG; - - // Remaining (non-overlap) sub-tiles of the overlap WG. - auto process_non_overlap_subs = [&]() { - CUTLASS_PRAGMA_UNROLL - for (uint32_t s = 0; s < SubTilesPerWG; s++) { - uint32_t sub_idx = wg_sub_base + s; - if (sub_idx < ovlp_sub_base || - sub_idx >= ovlp_sub_base + OverlapSubCount) { - process_sub(sub_idx); - } - } - }; - - if constexpr (KernelTraits::KOverlapSingleLoad) { - // Overlap region fits one TMEM load: T2R, arrive, then - // R2G, so MMA resumes without waiting for the stores. - cute::Tensor acc_ovlp_tile = - cute::flat_divide(acc, OverlapLoadTile{}); - cute::TiledCopy tiled_t2r_ovlp = cute::make_tmem_copy( - CopyOpT2R_Overlap{}, - acc_ovlp_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, - cute::_0{})); - auto tx_ovlp = threadIdx.x % cute::size(tiled_t2r_ovlp); - cute::ThrCopy thread_t2r_ovlp = - tiled_t2r_ovlp.get_slice(tx_ovlp); - - cute::Tensor thr_tacc_src_ovlp = - thread_t2r_ovlp.partition_S(acc_ovlp_tile); - cute::Tensor thr_demo_ovlp = thread_t2r_ovlp.partition_D( - acc_ovlp_tile(cute::_, cute::_, cute::_0{}, cute::_0{}, - cute::_0{})); - cute::Tensor thr_racc_dst_ovlp = - cute::make_tensor( - cute::shape(thr_demo_ovlp)); - cute::Tensor thr_rd_ovlp = - cute::make_tensor(cute::shape(thr_demo_ovlp)); - - cute::Tensor gD_ovlp_tile = - cute::flat_divide(gD, OverlapLoadTile{}); - auto tiled_r2g_ovlp = [&]() { - if constexpr (SwapAB) { - return cute::make_tiled_copy_D( - cute::Copy_Atom, - TypeD>{}, - tiled_t2r_ovlp); - } else { - return cute::make_tiled_copy_D( - cute::Copy_Atom< - cute::SM100_STORE_256bit_CACHE_NOALLOCATION, - TypeD>{}, - tiled_t2r_ovlp); - } - }(); - auto thr_r2g_ovlp = tiled_r2g_ovlp.get_slice(tx_ovlp); - cute::Tensor src_ovlp = thr_r2g_ovlp.retile_S(thr_rd_ovlp); - cute::Tensor dst_ovlp = - thr_r2g_ovlp.partition_D(gD_ovlp_tile); - - static constexpr int WideTilesTotal = - KernelTraits::KWideTilesTotal; - uint32_t ovlp_wide_idx = (epilogue_stage_idx % 2 == 0) - ? (WideTilesTotal - 1) - : 0; - - if (warp_group_idx == overlap_wg) { - cute::copy(tiled_t2r_ovlp, - thr_tacc_src_ovlp( - cute::_, cute::_, cute::_, cute::_0{}, - ovlp_wide_idx, epilogue_stage_idx), - thr_racc_dst_ovlp); - cutlass::arch::fence_view_async_tmem_load(); - } - - // Overlap columns read; MMA may proceed. - if (warp_group_idx == overlap_wg) { - overlap_arrive(shared_storage, cta_v, warp_group_idx); - } - - if (warp_group_idx == overlap_wg) { - { - constexpr int kN = - decltype(cute::size(thr_rd_ovlp))::value; - using Converter = - cutlass::NumericArrayConverter< - TypeD, TypeAccumulate, kN>; - auto& src_arr = reinterpret_cast< - cutlass::Array const&>( - *thr_racc_dst_ovlp.data()); - auto& dst_arr = reinterpret_cast< - cutlass::Array&>( - *thr_rd_ovlp.data()); - if constexpr (HasAlpha) { - CUTLASS_PRAGMA_UNROLL - for (int i = 0; i < kN; ++i) { - src_arr[i] *= alpha_val; - } - } - dst_arr = Converter::convert(src_arr); - } - - auto dst_cur = cute::make_tensor( - dst_ovlp.data() + row_shift, - dst_ovlp.layout())((cute::_, cute::_), cute::_, - cute::_, cute::Int<0>{}, - ovlp_wide_idx, block_m_idx, - n_idx); - - if constexpr (SwapAB) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t v_id = 0; v_id < src_ovlp.size(); - ++v_id) { - auto* addr = (TypeD*)&dst_cur(v_id); - auto val = src_ovlp[v_id]; - asm volatile( - "st.global.L1::no_allocate.b16 " - "[%0], %1;" - : - : "l"(addr), "h"(*(uint16_t*)&val)); - } - } else { - cute::copy(tiled_r2g_ovlp, src_ovlp, dst_cur); - } - - process_non_overlap_subs(); - } - } else { - // No single TMEM load covers the overlap region: do - // T2R + R2G per sub-tile, then arrive after the last read. - if (warp_group_idx == overlap_wg) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t o = 0; o < OverlapSubCount; o++) { - process_sub(ovlp_sub_base + o); - } - } - - if (warp_group_idx == overlap_wg) { - overlap_arrive(shared_storage, cta_v, warp_group_idx); - } - - if (warp_group_idx == overlap_wg) { - process_non_overlap_subs(); - } - } - - if (warp_group_idx != overlap_wg) { - CUTLASS_PRAGMA_UNROLL - for (uint32_t s = 0; s < SubTilesPerWG; s++) { - process_sub(wg_sub_base + s); - } - } - } else { - uint32_t wg_sub_base = warp_group_idx * SubTilesPerWG; - CUTLASS_PRAGMA_UNROLL - for (uint32_t s = 0; s < SubTilesPerWG; s++) { - process_sub(wg_sub_base + s); - } - } - - if constexpr (KernelTraits::SkipTmemFence) { - // One fence after the last TMEM load, before releasing the - // stage (instead of one per load). - cutlass::arch::fence_view_async_tmem_load(); - } - acc_pipeline.consumer_release(acc_pipe_consumer_state); - ++acc_pipe_consumer_state; - - scheduler.advance(); - } - } - // KStreamK: tail-only stream-K instantiation (BF16 only). template CUTLASS_DEVICE void epilogue(Params const& epilogue_params, @@ -1184,11 +751,7 @@ class CollectiveEpilogue { SharedStorage& shared_storage, TmemStorage& tmem_storage, int warp_idx, TileScheduler& scheduler) { - if constexpr (KernelTraits::KIsBF16) { - epilogue_bf16(epilogue_params, acc_pipeline, - shared_storage, tmem_storage, warp_idx, - scheduler); - } else if constexpr (KernelTraits::KSwapStaged) { + if constexpr (KernelTraits::KSwapStaged) { epilogue_swap(epilogue_params, acc_pipeline, shared_storage, tmem_storage, warp_idx, scheduler); } else { @@ -1228,6 +791,20 @@ class CollectiveEpilogue { tiled_t2r_sub.get_slice(tx).partition_D(acc_sub_tile( cute::_, cute::_, cute::_0{}, cute::_0{}, cute::_0{})))); constexpr int kN = decltype(cute::size(thr_rd_sub))::value; + static_assert(decltype(cute::size(tiled_t2r_sub))::value == + cutlass::NumThreadsPerWarpGroup); + // The raw unit load assumes N in TMEM columns (32dp, 4x1); BF16 + // tiles also use the 16dp (64-row CTA) and 2SM "2x2" layouts, so + // they load through the partitioned tiled copy instead. + constexpr bool kPartitionedLoad = KernelTraits::KIsBF16; + // BF16 tiles never straddle a batch (the host requires whole + // tiles), so they clip against the stacked D; a per-batch bound + // keeps the batch range live across the store loop and spills. + constexpr bool kClipWholeD = KernelTraits::KIsBF16; + cute::Tensor thr_tacc_src_sub = + tiled_t2r_sub.get_slice(tx).partition_S(acc_sub_tile); + cute::Tensor thr_racc_sub = + cute::make_tensor(cute::shape(thr_rd_sub)); const auto shape_d = SwapAB ? cute::make_shape(out_n, out_m, 1) : cute::make_shape(out_m, out_n, 1); cute::Tensor mD = cute::make_tensor( @@ -1261,6 +838,47 @@ class CollectiveEpilogue { shared_storage.tensor_sC(), OverlapComputeTile{})); cute::Tensor thr_rC_sub = cute::make_tensor(cute::shape(thr_rd_sub)); + const TileRows whole_d{ + 0, out_m, 0, + out_m % (SwapAB ? KernelTraits::KBlockN + : KernelTraits::KBlockM) == + 0}; + const auto clip_rows = [&](const TileRows& rows) -> const TileRows& { + if constexpr (kClipWholeD) { + return whole_d; + } else { + return rows; + } + }; + + // Stream-K partials go to a compact per-CTA [CtaShape_M][KBlockN] + // slot, through the D store's thread layout. Built once: building + // it per sub-tile spills. Empty when !KStreamK. + constexpr int kPartialM = cute::size<0>(CtaShape_MNK{}); + constexpr int kPartialN = cute::size<1>(CtaShape_MNK{}); + auto partial_store = [&]() { + if constexpr (KStreamK) { + auto tiled_p = cute::make_tiled_copy_D( + cute::Copy_Atom< + cute::AutoVectorizingCopyWithAssumedAlignment<128>, + TypeAccumulate>{}, + tiled_t2r_sub); + auto thr_p = tiled_p.get_slice(tx); + return cute::make_tuple( + tiled_p, thr_p.retile_S(thr_racc_sub), + thr_p.partition_D(cute::flat_divide( + cute::make_tensor( + cute::make_gmem_ptr(epilogue_params.ptr_partial), + cute::make_layout( + cute::make_shape(cute::Int{}, + cute::Int{}), + cute::make_stride(cute::Int{}, + cute::_1{}))), + OverlapComputeTile{}))); + } else { + return cute::make_tuple(); + } + }(); uint8_t* const stage = reinterpret_cast(&shared_storage) + KStagedSmem + @@ -1286,7 +904,17 @@ class CollectiveEpilogue { alpha = shared_storage.alpha[scheduler.expert_idx()]; } const int64_t bcol0 = batch_col0(epilogue_params, scheduler); - const int64_t row_shift = bcol0 - (int64_t)rows.lo * d_ld; + const int64_t row_shift = + d_shift(epilogue_params, scheduler, rows); + // < 0: this tile stores its final result. + [[maybe_unused]] int partial_slot = -1; + [[maybe_unused]] int64_t partial_off = 0; + if constexpr (KStreamK) { + partial_slot = scheduler.partial_slot(); + partial_off = + (static_cast(partial_slot) * KNumCTA + cta_v) * + kPartialM * kPartialN; + } const int64_t row = (int64_t)rows.row0 + tx; const bool row_ok = row >= (int64_t)rows.lo && row < (int64_t)rows.hi; @@ -1333,7 +961,15 @@ class CollectiveEpilogue { << 16) + wg * kCols; const auto load_unit = [&](int u, uint32_t(&r)[kU]) { - copy_to_regs(acc + u * kU, r); + if constexpr (kPartitionedLoad) { + cute::copy(tiled_t2r_sub, + thr_tacc_src_sub(cute::_, cute::_, cute::_, + cute::_0{}, wg * kUnits + u, + stage_idx), + thr_racc_sub); + } else { + copy_to_regs(acc + u * kU, r); + } }; const auto consume = [&](int u, const uint32_t(&r)[kU]) { if constexpr (KGlu) { @@ -1376,13 +1012,32 @@ class CollectiveEpilogue { } } else { const int sub_idx = wg * kUnits + u; - if constexpr (KernelTraits::IsSfbUnaligned && !SwapAB) { + // The last N tile overhangs N (unaligned-SFB pair + // tiles, BF16 N-tails); a sub-tile is all in or all + // out because N is a multiple of the sub-tile width. + if constexpr ((KernelTraits::IsSfbUnaligned && + !SwapAB) || + KernelTraits::KEpiNeedsNPredicate) { if (n_idx * cute::size<1>(TileShape{}) + sub_idx * kSubN >= out_n) { return; } } + // Stream-K tail chunk: store the raw fp32 + // accumulator; the reduce kernel sums and casts. + if constexpr (KStreamK) { + if (partial_slot >= 0) { + auto dst_p = cute::get<2>(partial_store); + dst_p.data() = dst_p.data() + partial_off; + cute::copy(cute::get<0>(partial_store), + cute::get<1>(partial_store), + dst_p((cute::_, cute::_), cute::_, + cute::_, cute::Int<0>{}, + sub_idx)); + return; + } + } if constexpr (AddBias) { cute::copy( tiled_s2r_bias, @@ -1393,7 +1048,11 @@ class CollectiveEpilogue { cutlass::Array f; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < kN; ++i) { - f[i] = __uint_as_float(r[i]) * alpha; + if constexpr (kPartitionedLoad) { + f[i] = thr_racc_sub(i) * alpha; + } else { + f[i] = __uint_as_float(r[i]) * alpha; + } if constexpr (AddBias && KAct) { f[i] += static_cast(thr_rC_sub[i]); } @@ -1418,7 +1077,7 @@ class CollectiveEpilogue { dst_coords_sub((cute::_, cute::_), cute::_, cute::_, cute::Int<0>{}, sub_idx, block_m_idx, n_idx), - rows); + clip_rows(rows)); } }; const bool ovlp_wg = diff --git a/csrc/kernel/gemm/kernel_traits.cuh b/csrc/kernel/gemm/kernel_traits.cuh index b847c9d..569eaff 100644 --- a/csrc/kernel/gemm/kernel_traits.cuh +++ b/csrc/kernel/gemm/kernel_traits.cuh @@ -204,9 +204,6 @@ struct GemmKernelTraits { using OverlapComputeTile = cute::conditional_t< KSubTileN == KEpiComputeN, EpiComputeTile, cute::Shape, cute::Int>>; - static constexpr int KSubTilesPerWG = KEpiComputeN / KSubTileN; - // Overlap sub-tiles sit at the boundary between adjacent stages. - static constexpr int KOverlapSubCount = KTmemOverlapCols / KSubTileN; // Overlap region fits one TMEM load (widths with a hardware op), so MMA can // resume right after T2R; other widths (e.g. 48) interleave per sub-tile. static constexpr bool KOverlapSingleLoad = @@ -262,34 +259,6 @@ struct GemmKernelTraits { "KEpilogueWarpGroupsOverride = 1) or warps 2/3 address " "outside the tile and the output is silently wrong."); - // CopyOp for the whole overlap region when KOverlapSingleLoad; width - // matched to KTmemOverlapCols, else 16x. - using CopyOpT2R_Overlap = cute::conditional_t< - KEpiTmemDp == 16, - // 16dp: N repeat halved relative to the 32dp column below. - cute::conditional_t< - KTmemOverlapCols == 16, cute::SM100_TMEM_LOAD_16dp32b8x, - cute::conditional_t< - KTmemOverlapCols == 32, cute::SM100_TMEM_LOAD_16dp32b16x, - cute::conditional_t>>, - cute::conditional_t< - KTmemOverlapCols == 16, cute::SM100_TMEM_LOAD_32dp32b16x, - cute::conditional_t< - KTmemOverlapCols == 32, cute::SM100_TMEM_LOAD_32dp32b32x, - cute::conditional_t>>>; - - static constexpr int KOverlapLoadN = - KOverlapSingleLoad ? KTmemOverlapCols - : (KTmemOverlapCols == 0 ? 16 : KSubTileN); - using OverlapLoadTile = - cute::Shape, cute::Int>; - - static constexpr int KWideTilesTotal = KBlockN / KOverlapLoadN; - // T2R op for EpiComputeTile N (and CtaM). `Nx` is the column count; a // mismatched width moves the wrong columns, so every reachable width needs // its own arm. The 16dp series (CtaM=64) uses half-width atoms. From 8ead9543f23eae9b41550ff20ea0f7a4ef6a2d0c Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 26 Nov 2026 05:02:57 +0800 Subject: [PATCH 12/14] refactor(gemm): name the quantized D store as a store policy The quantized-output branch of the R2G sub-tile loop (UE8M0 scale per kGroup columns, e4m3 data through the SMEM stage and TMA, direct stores for rows above the box, then the row's scale word) moves out of the loop body into store_quant, defined next to the loop's other per-tile state. The loop now reads as load, transform, store, with one named store per output: store_rows (R2G), the stream-K partial store, and store_quant. The body moves verbatim; buf_i is declared ahead of the lambda, and expert_idx is passed in. Codegen against 032ac47: resource usage of all 1238 gemm kernels is unchanged (registers, stack, no spill). The instruction streams of 66 quantized kernels (128x64 / 128x128 / 128x256 / 256x64 / 256x128 / 256x256 with Quant, GateMulQuant, SituQuant, SigmoidGateMulQuant) differ only in the order of two adjacent independent zero moves (UMOV UR8, URZ / UMOV UR24, URZ) at four sites, checked on a single-tile build of 128x128 Quant: same instruction count, same registers, otherwise identical SASS. No other function changes. Verified: the four GEMM test files pass (183 passed, 2 xfailed). Co-Authored-By: Claude Code --- csrc/kernel/gemm/epilogue.cuh | 131 ++++++++++++++++++---------------- 1 file changed, 71 insertions(+), 60 deletions(-) diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index 2671ea0..83af9a0 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -891,6 +891,75 @@ class CollectiveEpilogue { } int buf_i = 0; + // Quantized D: one UE8M0 scale per kGroup columns, e4m3 data via + // the SMEM stage and TMA (direct stores for rows above the box), + // then the row's scale word. + const auto store_quant = [&](const __nv_bfloat162* vals, + const TileRows& rows, int64_t row, + bool row_ok, int64_t bcol0, int col0, + uint32_t expert) { + const int32_t box_row = + (int32_t)((int64_t)rows.row0 - (int64_t)rows.lo); + SfWord sf_word = 0; + CUTLASS_PRAGMA_UNROLL + for (int g = 0; g < kGroups; ++g) { + const __nv_bfloat162* v = &vals[g * kGroup / 2]; + const uint32_t m = exp8_pair(abs_max(v)); + const uint32_t e = + scale_of_exp8(::max(m & 0xffffu, m >> 16)); + sf_word |= (SfWord)(e << (8 * g)); + const uint32_t sc_bits = multiplier_bits(e) * 0x10001u; + const __nv_bfloat162 sc = + reinterpret_cast(sc_bits); + uint32_t q[kGroup / 4]; + CUTLASS_PRAGMA_UNROLL + for (int i = 0; i < kGroup / 4; ++i) { + q[i] = e4m3x4(v[2 * i], v[2 * i + 1], sc); + } + const uint4 lo = make_uint4(q[0], q[1], q[2], q[3]); + const uint4 hi = make_uint4(q[4], q[5], q[6], q[7]); + if (box_row < 0) { + if (row_ok) { + uint4* dst = reinterpret_cast( + reinterpret_cast( + epilogue_params.ptr_d) + + d_row(epilogue_params, rows, row) + bcol0 + + col0 + g * kGroup); + dst[0] = lo; + dst[1] = hi; + } + continue; + } + uint8_t* buf = + stage + buf_i * KernelTraits::KEpiBufBytes; + *reinterpret_cast(buf + st_off + st_x) = lo; + *reinterpret_cast(buf + st_off + + (st_x ^ KVec)) = hi; + cutlass::arch::fence_view_async_shared(); + if (issuer) { + cute::tma_store_wait<0>(); + } + cutlass::arch::NamedBarrier::sync( + cutlass::NumThreadsPerWarpGroup, KEpiBarrier + wg); + if (issuer) { + cute::SM90_TMA_STORE_3D::copy( + &epilogue_params.d_desc, buf, col0 + g * kGroup, + box_row, + KernelTraits::KernelType == KernelMode::Batch + ? (int32_t)expert + : 0); + cute::tma_store_arrive(); + } + buf_i ^= 1; + } + if (row_ok) { + *reinterpret_cast( + epilogue_params.ptr_sfd + + sf_offset(epilogue_params, rows, row, + bcol0 + col0)) = sf_word; + } + }; + AccumulatorPipelineState acc_pipe_consumer_state; BiasPipelineState bias_pipe_consumer_state; while (scheduler.is_valid()) { @@ -1118,66 +1187,8 @@ class CollectiveEpilogue { } if constexpr (KQuantD) { - const int32_t box_row = - (int32_t)((int64_t)rows.row0 - (int64_t)rows.lo); - SfWord sf_word = 0; - CUTLASS_PRAGMA_UNROLL - for (int g = 0; g < kGroups; ++g) { - const __nv_bfloat162* v = &vals[g * kGroup / 2]; - const uint32_t m = exp8_pair(abs_max(v)); - const uint32_t e = - scale_of_exp8(::max(m & 0xffffu, m >> 16)); - sf_word |= (SfWord)(e << (8 * g)); - const uint32_t sc_bits = multiplier_bits(e) * 0x10001u; - const __nv_bfloat162 sc = - reinterpret_cast(sc_bits); - uint32_t q[kGroup / 4]; - CUTLASS_PRAGMA_UNROLL - for (int i = 0; i < kGroup / 4; ++i) { - q[i] = e4m3x4(v[2 * i], v[2 * i + 1], sc); - } - const uint4 lo = make_uint4(q[0], q[1], q[2], q[3]); - const uint4 hi = make_uint4(q[4], q[5], q[6], q[7]); - if (box_row < 0) { - if (row_ok) { - uint4* dst = reinterpret_cast( - reinterpret_cast( - epilogue_params.ptr_d) + - d_row(epilogue_params, rows, row) + bcol0 + - col0 + g * kGroup); - dst[0] = lo; - dst[1] = hi; - } - continue; - } - uint8_t* buf = - stage + buf_i * KernelTraits::KEpiBufBytes; - *reinterpret_cast(buf + st_off + st_x) = lo; - *reinterpret_cast(buf + st_off + - (st_x ^ KVec)) = hi; - cutlass::arch::fence_view_async_shared(); - if (issuer) { - cute::tma_store_wait<0>(); - } - cutlass::arch::NamedBarrier::sync( - cutlass::NumThreadsPerWarpGroup, KEpiBarrier + wg); - if (issuer) { - cute::SM90_TMA_STORE_3D::copy( - &epilogue_params.d_desc, buf, col0 + g * kGroup, - box_row, - KernelTraits::KernelType == KernelMode::Batch - ? (int32_t)scheduler.expert_idx() - : 0); - cute::tma_store_arrive(); - } - buf_i ^= 1; - } - if (row_ok) { - *reinterpret_cast( - epilogue_params.ptr_sfd + - sf_offset(epilogue_params, rows, row, - bcol0 + col0)) = sf_word; - } + store_quant(vals, rows, row, row_ok, bcol0, col0, + scheduler.expert_idx()); } scheduler.advance(); } From 70f16f3c873ec328f325d0e5e5e3b4cccaa1a402 Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Thu, 26 Nov 2026 06:27:55 +0800 Subject: [PATCH 13/14] refactor(gemm): share the per-expert alpha load between the epilogue families The staged SwapAB loop and the R2G sub-tile loop each spelled out "this tile's expert alpha, or 1 without alpha"; both now call tile_alpha. With this the two families share every per-tile header helper (tile_rows, batch_col0, d_row, pair_rank, tile_alpha). The tile tail stays per family: the staged loop releases the accumulator stage mid-pipeline, the R2G loop after the last sub-tile load. Codegen against 3c1e1af: SASS of all 1374 functions is identical. Verified: the four GEMM test files pass (183 passed, 2 xfailed). Co-Authored-By: Claude Code --- csrc/kernel/gemm/epilogue.cuh | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index 83af9a0..b6f84d2 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -293,6 +293,16 @@ class CollectiveEpilogue { return 0; } } + // Per-expert alpha of the current tile; 1 when the traits carry none. + CUTLASS_DEVICE static float tile_alpha( + SharedStorage const& shared_storage, + TileScheduler const& scheduler) { + if constexpr (HasAlpha) { + return shared_storage.alpha[scheduler.expert_idx()]; + } else { + return 1.0f; + } + } CUTLASS_DEVICE static int64_t d_row(Params const& p, TileRows const& rows, int64_t row) { return (row - (int64_t)rows.lo) * p.d_ld; @@ -480,10 +490,7 @@ class CollectiveEpilogue { const auto chunk_row = [&](int i) { return (int64_t)rows.row0 + (wg + i * KEpilogueWgs) * kChunk; }; - float alpha = 1.0f; - if constexpr (HasAlpha) { - alpha = shared_storage.alpha[scheduler.expert_idx()]; - } + const float alpha = tile_alpha(shared_storage, scheduler); uint32_t g[KGateMul ? kMyChunks : 1][kLoads][kQuad]; if constexpr (KGateMul) { const TypeC* base = epilogue_params.ptr_gate + col0 + @@ -968,10 +975,7 @@ class CollectiveEpilogue { scheduler.m_idx() * KNumCTA + cta_v; const TileRows rows = tile_rows(scheduler, out_m, block_m_idx, n_idx); - float alpha = 1.0f; - if constexpr (HasAlpha) { - alpha = shared_storage.alpha[scheduler.expert_idx()]; - } + const float alpha = tile_alpha(shared_storage, scheduler); const int64_t bcol0 = batch_col0(epilogue_params, scheduler); const int64_t row_shift = d_shift(epilogue_params, scheduler, rows); From 9ecb98bca452d776de6f70939c72e91f9d7a5152 Mon Sep 17 00:00:00 2001 From: Yuhan Xu Date: Wed, 2 Dec 2026 22:40:50 +0800 Subject: [PATCH 14/14] style(gemm): trim redundant comments across BF16 paths Remove debugging notes, stale performance claims, device-specific examples and explanations that repeat the code across the BF16 PR. Keep concise hardware, layout, synchronization and API contracts. Apply CI-pinned formatting and EOF fixes without changing executable tokens or configuration values. Keep performance changes parked. Co-Authored-By: Claude Code --- benchmark/ci_configs/gemm/batch_bf16.yaml | 5 +- benchmark/ci_configs/gemm/dense_bf16.yaml | 4 - benchmark/configs/gemm/batch_bf16.yaml | 17 +-- benchmark/configs/gemm/dense_bf16.yaml | 31 ++--- .../configs/gemm/group_contiguous_bf16.yaml | 7 +- benchmark/configs/gemm/group_masked_bf16.yaml | 7 +- benchmark/kernel/gemm/backends/deepgemm.py | 7 - benchmark/kernel/gemm/backends/flashinfer.py | 11 +- benchmark/kernel/gemm/backends/golden.py | 8 +- benchmark/kernel/gemm/scenarios/batch_gemm.py | 36 +----- benchmark/kernel/gemm/scenarios/dense_gemm.py | 4 - .../kernel/gemm/scenarios/grouped_gemm.py | 2 - ci/baselines/gemm/batch_bf16.json | 2 +- ci/baselines/gemm/dense_bf16.json | 2 +- csrc/common/cpp_extensions.cc | 23 ++-- csrc/kernel/gemm/batch_gemm.cu | 24 ++-- csrc/kernel/gemm/dense_gemm.cu | 19 ++- csrc/kernel/gemm/epilogue.cuh | 71 ++++------- csrc/kernel/gemm/gemm_dispatch.cuh | 119 ++++------------- csrc/kernel/gemm/gemm_kernel.cuh | 43 ++----- csrc/kernel/gemm/gemm_tile.cuh | 71 ++--------- csrc/kernel/gemm/group_contiguous_gemm.cu | 18 ++- csrc/kernel/gemm/group_masked_gemm.cu | 18 ++- csrc/kernel/gemm/kernel_traits.cuh | 120 +++++------------- csrc/kernel/gemm/mainloop_fwd.cuh | 70 ++++------ csrc/kernel/gemm/stream_k_reduce.cuh | 12 +- csrc/kernel/gemm/tile_scheduler.cuh | 90 +++---------- csrc/kernel/gemm/utils.cuh | 6 +- halops/gemm/batch_gemm.py | 4 +- tests/test_batch_gemm.py | 10 +- tests/test_dense_gemm.py | 9 +- tests/test_group_contiguous_gemm.py | 10 +- tests/test_group_masked_gemm.py | 15 +-- 33 files changed, 235 insertions(+), 660 deletions(-) diff --git a/benchmark/ci_configs/gemm/batch_bf16.yaml b/benchmark/ci_configs/gemm/batch_bf16.yaml index 172c94f..cb3fce8 100644 --- a/benchmark/ci_configs/gemm/batch_bf16.yaml +++ b/benchmark/ci_configs/gemm/batch_bf16.yaml @@ -1,10 +1,7 @@ scenario: batch_gemm mode: bf16 -# CI regression subset for native BF16 batch GEMM, mirroring the shapes in -# benchmark/configs/gemm/batch_bf16.yaml. halops-only + refcheck off, per the -# ci_configs convention (baseline comparison is halops-vs-baseline). -# [B, M, N, K]. +# Shapes: [B, M, N, K]. shapes: - [8, 8192, 1024, 4096] - [8192, 64, 128, 4096] diff --git a/benchmark/ci_configs/gemm/dense_bf16.yaml b/benchmark/ci_configs/gemm/dense_bf16.yaml index 193da81..3f129fa 100644 --- a/benchmark/ci_configs/gemm/dense_bf16.yaml +++ b/benchmark/ci_configs/gemm/dense_bf16.yaml @@ -1,10 +1,6 @@ scenario: dense_gemm mode: bf16 -# CI regression subset for native BF16 dense GEMM, mirroring the routine -# 10-shape preset in benchmark/configs/gemm/dense_bf16.yaml. -# halops-only + refcheck off, per the ci_configs convention (baseline -# comparison is halops-vs-baseline). shapes: - [64, 4096, 4096] - [64, 32768, 1024] diff --git a/benchmark/configs/gemm/batch_bf16.yaml b/benchmark/configs/gemm/batch_bf16.yaml index 903c2c5..38565a4 100644 --- a/benchmark/configs/gemm/batch_bf16.yaml +++ b/benchmark/configs/gemm/batch_bf16.yaml @@ -1,28 +1,13 @@ -# Batch GEMM BF16 baseline: representative model shapes vs cuBLAS (torch.bmm). -# -# The [B, M, N, K] convention: batch item b computes input[b] @ weight[b]^T, -# i.e. [M, K] @ [K, N] -> [M, N]. batch_gemm dispatches on total_m = B*M. -# -# Backends: -# halops -- our native BF16 batch GEMM (3-tier dispatch: 256x256 pair / -# 128x256 / SwapAB 128x64) -# fi -- flashinfer.bmm_bf16, cuDNN backend (the default the dense -# bf16 path also uses) -# fi_cutlass -- flashinfer.bmm_bf16, CUTLASS backend, so flashinfer's own -# kernels and its cuDNN fallback can be told apart -# bmm -- torch.bmm (cuBLAS) +# Shapes: [B, M, N, K]. scenario: batch_gemm mode: bf16 shapes: - # batched output projection (8 experts) - [8, 8192, 1024, 4096] - # per-token bmms (batch=8192, M=64) - [8192, 64, 128, 4096] - [8192, 64, 512, 576] - [8192, 64, 512, 64] - [8192, 64, 256, 64] - # smaller batch variants to cover the dispatch tiers - [8, 1024, 4096, 4096] - [8, 128, 4096, 4096] - [4, 256, 7168, 4096] diff --git a/benchmark/configs/gemm/dense_bf16.yaml b/benchmark/configs/gemm/dense_bf16.yaml index fa8d7de..3931f1b 100644 --- a/benchmark/configs/gemm/dense_bf16.yaml +++ b/benchmark/configs/gemm/dense_bf16.yaml @@ -1,27 +1,16 @@ -# configs/gemm/dense_bf16.yaml -# Default quick preset: 10 shapes, for routine runs. Picks one or two -# representatives per M-based dispatch tier in DenseGemm (dense_gemm.cu), plus -# the odd-N shapes and the biggest absolute-loss shape. -# -# M=64 x2 thin-M non-swap rung (incl. widest N=32768) -# M=128 x2 thin-M / 96-wide rung (incl. narrow N=128) -# M=256 x1 mid-M ladder entry -# M=1024 x3 mid-M valley + N=1600 + widest N -# M=4096 x1 large-M square -# M=8192 x1 large-M, N=32768 family scenario: dense_gemm mode: bf16 shapes: - - [64, 4096, 4096] # thin-M - - [64, 32768, 1024] # thin-M widest N - - [128, 4096, 4096] # thin-M / 96-wide rung - - [128, 128, 4096] # narrow N - - [256, 4096, 4096] # mid-M ladder entry - - [1024, 4096, 4096] # mid-M valley - - [1024, 1600, 4096] # N=1600 (predicated N-tail) - - [1024, 32768, 1024] # mid-M widest N - - [4096, 4096, 4096] # large-M square - - [8192, 32768, 1024] # large-M, biggest absolute-loss shape + - [64, 4096, 4096] + - [64, 32768, 1024] + - [128, 4096, 4096] + - [128, 128, 4096] + - [256, 4096, 4096] + - [1024, 4096, 4096] + - [1024, 1600, 4096] + - [1024, 32768, 1024] + - [4096, 4096, 4096] + - [8192, 32768, 1024] sm_count: -1 backends: [halops, fi, deepgemm] diff --git a/benchmark/configs/gemm/group_contiguous_bf16.yaml b/benchmark/configs/gemm/group_contiguous_bf16.yaml index b2ba1fd..e222900 100644 --- a/benchmark/configs/gemm/group_contiguous_bf16.yaml +++ b/benchmark/configs/gemm/group_contiguous_bf16.yaml @@ -1,12 +1,7 @@ -# configs/gemm/group_contiguous_bf16.yaml -# Grouped contiguous native BF16 GEMM (mode="bf16") on the self-developed -# CollectiveMainloop. No quantization / scale factors; the golden -# torch.matmul (bf16, no dequant) is the refcheck reference. scenario: group_contiguous mode: bf16 -# [num_experts, max_m, N, K] shapes (total m = num_experts * max_m, aligned to -# tile_m boundaries). N a multiple of 256, K a multiple of 64. +# Shapes: [num_experts, max_m, N, K]. shapes: - [4, 128, 256, 512] - [4, 256, 1024, 1024] diff --git a/benchmark/configs/gemm/group_masked_bf16.yaml b/benchmark/configs/gemm/group_masked_bf16.yaml index 577fef6..118de54 100644 --- a/benchmark/configs/gemm/group_masked_bf16.yaml +++ b/benchmark/configs/gemm/group_masked_bf16.yaml @@ -1,12 +1,7 @@ -# configs/gemm/group_masked_bf16.yaml -# Grouped masked native BF16 GEMM (mode="bf16") on the self-developed -# CollectiveMainloop. No quantization / scale factors; the golden -# torch.matmul (bf16, no dequant) is the refcheck reference. scenario: group_masked mode: bf16 -# [num_experts, max_m, N, K] shapes. max_m must be a multiple of the tile_m -# (128), N a multiple of 256, K a multiple of 64. +# Shapes: [num_experts, max_m, N, K]. shapes: - [4, 128, 256, 512] - [4, 256, 1024, 1024] diff --git a/benchmark/kernel/gemm/backends/deepgemm.py b/benchmark/kernel/gemm/backends/deepgemm.py index 0061370..b28ed5f 100644 --- a/benchmark/kernel/gemm/backends/deepgemm.py +++ b/benchmark/kernel/gemm/backends/deepgemm.py @@ -69,8 +69,6 @@ def make_dense_inputs(x_bf16: torch.Tensor, w_bf16: torch.Tensor, mode: str) -> out = torch.empty(m, n, dtype=torch.bfloat16, device=x_bf16.device) if mode == "bf16": - # Native BF16: no quantization / scale factors. bf16_gemm_nt computes - # a @ b.T, so pass w_bf16 [N, K] directly as b. return { "a": x_bf16, "b": w_bf16, @@ -123,8 +121,6 @@ def make_grouped_masked_inputs( masked_m = masked_m.to(device=dev, dtype=torch.int32) if mode == "bf16": - # Native BF16: 3D masked layout, no quantization / scale factors. - # m_grouped_bf16_gemm_nt_masked computes a @ b.T per group. out = torch.empty(num_groups, max_m, n, dtype=torch.bfloat16, device=dev) return { "a": a_bf16, @@ -218,9 +214,6 @@ def make_grouped_contiguous_inputs( m_indices = m_indices.to(device=dev, dtype=torch.int32) if mode == "bf16": - # Native BF16: 2D contiguous layout, no quantization / scale factors. - # m_grouped_bf16_gemm_nt_contiguous computes a @ b.T with per-row expert - # routing given by m_indices. out = torch.empty(m, n, dtype=torch.bfloat16, device=dev) return { "a": x_bf16, diff --git a/benchmark/kernel/gemm/backends/flashinfer.py b/benchmark/kernel/gemm/backends/flashinfer.py index 29ba25c..54fb2d1 100644 --- a/benchmark/kernel/gemm/backends/flashinfer.py +++ b/benchmark/kernel/gemm/backends/flashinfer.py @@ -48,9 +48,6 @@ def run_fi_dense_gemm(inp: dict): mode = inp.get("mode", "w8a8-mxfp8") backend = _fi_backend(inp) if mode == "bf16": - # flashinfer's CUTLASS bf16 kernel is not sm100-tuned (~18% roofline); - # its documented default backend "cudnn" is ~2x faster on large shapes. - # Keep it overridable via inp["backend"] for per-shape experiments. return flashinfer.mm_bf16( inp["x"], inp["w"].T, @@ -86,13 +83,7 @@ def run_fi_dense_gemm(inp: dict): def run_fi_batch_gemm(inp: dict): - """Run FlashInfer batched BF16 GEMM (bmm_bf16). - - This is FlashInfer's counterpart to torch.bmm for the per-token / per-expert - batched shapes. Like the dense bf16 path, its default "cudnn" backend is the - fast one; the CUTLASS one is offered separately so the gap between - FlashInfer's own kernels and its cuDNN fallback stays visible. - """ + """Run FlashInfer batched BF16 GEMM.""" _check() import flashinfer diff --git a/benchmark/kernel/gemm/backends/golden.py b/benchmark/kernel/gemm/backends/golden.py index 80b5342..cca7332 100644 --- a/benchmark/kernel/gemm/backends/golden.py +++ b/benchmark/kernel/gemm/backends/golden.py @@ -94,7 +94,6 @@ def run_dense_golden(inp: dict) -> torch.Tensor: """ mode = inp.get("mode", "w8a8-mxfp8") if mode == "bf16": - # Native BF16: the kernel consumes bf16 directly, no quantization noise. x = inp["x_bf16"] w = inp["w_bf16"] else: @@ -124,13 +123,12 @@ def run_grouped_golden(inp: dict) -> torch.Tensor: """ mode = inp.get("mode", "w8a8-mxfp8") if mode == "bf16": - # Native BF16: the kernel consumes bf16 directly, no quantization noise. - x = inp["x_bf16"] # [M, K] + x = inp["x_bf16"] w_src = inp["w_bf16"] w = w_src else: - x = _dequant_to_bf16(inp["x_bf16"], mode) # [M, K] - w_src = inp["w_bf16"] # [E, N, K] + x = _dequant_to_bf16(inp["x_bf16"], mode) + w_src = inp["w_bf16"] num_groups, n, k = w_src.shape w = _dequant_to_bf16(w_src.reshape(num_groups * n, k), mode).reshape( num_groups, n, k diff --git a/benchmark/kernel/gemm/scenarios/batch_gemm.py b/benchmark/kernel/gemm/scenarios/batch_gemm.py index 5dc733a..be48e16 100644 --- a/benchmark/kernel/gemm/scenarios/batch_gemm.py +++ b/benchmark/kernel/gemm/scenarios/batch_gemm.py @@ -13,26 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -Batch GEMM benchmark scenario for BF16 on SM100. - -Mirrors dense_gemm.py's structure. Shapes are [B, M, N, K] where B is the -batch (expert) count, and each batch item computes output[b] = input[b] @ -weight[b]^T, i.e. [M, K] @ [K, N] -> [M, N]. - -The batch count B maps to GemmRowResult.num_experts so the existing output -infrastructure (header, table, CSV) renders it without modification. - -Backends: - halops -- our native BF16 batch GEMM (batch_gemm.cu, 3-tier dispatch) - fi -- flashinfer.bmm_bf16, cuDNN backend (same default as the dense - bf16 path) - fi_cutlass -- flashinfer.bmm_bf16, CUTLASS backend, so flashinfer's own - kernels and its cuDNN fallback can be told apart - bmm -- torch.bmm (cuBLAS batch GEMM), the reference the model - currently uses in production via aten::bmm - -deep_gemm has no batched BF16 entry point (dense/grouped only), so unlike the -dense scenario there is no deepgemm row here. +BF16 batch GEMM benchmark. Shapes: [B, M, N, K]. +Reports use num_experts=B and per-item m=M. """ from __future__ import annotations @@ -118,11 +100,7 @@ def adapt_bmm(inp: BatchGemmInput) -> dict: def adapt_fi(inp: BatchGemmInput, backend: str = "cudnn") -> dict: - """Inputs for flashinfer.bmm_bf16. - - It wants B as (b, k, n) column-major, which is exactly our (b, n, k) weight - transposed -- no copy, just strides on the tensor we already have. - """ + """Transpose weights [B, N, K] to a [B, K, N] view for FlashInfer.""" return { "x": inp.x, "bt": inp.w.transpose(-2, -1), @@ -231,7 +209,6 @@ def _refcheck_entry( inp["out"].zero_() run_fn(inp) torch.cuda.synchronize() - # Every backend writes the [B, M, N] layout. out = inp["out"] diff = (out.float() - ref_out.float()).abs() tol = refcheck_atol + refcheck_rtol * ref_out.float().abs() @@ -301,15 +278,16 @@ def run_scenario(cfg: dict) -> None: print(f"[{status}] {name} b={b},m={m},n={n},k={k}") continue + # FLOPs use total B*M; bandwidth and reports use B and per-item M. metrics = compute_gemm_metrics( timing, - b * m, # total M for FLOPs calculation + b * m, n, k, dtype_bytes=dtype_bytes, baseline_us=baseline_us, gpu_type=cfg.get("gpu_type", "b200"), - num_experts=b, # each expert loads [n, k] once + num_experts=b, ) if name == "halops": baseline_us = metrics.median_us @@ -319,7 +297,7 @@ def run_scenario(cfg: dict) -> None: row = GemmRowResult( scenario="batch_gemm", backend=name, - m=m, # per-batch-item M (total = b*m shown via num_experts) + m=m, n=n, k=k, mode=mode, diff --git a/benchmark/kernel/gemm/scenarios/dense_gemm.py b/benchmark/kernel/gemm/scenarios/dense_gemm.py index 018f7fb..3485569 100644 --- a/benchmark/kernel/gemm/scenarios/dense_gemm.py +++ b/benchmark/kernel/gemm/scenarios/dense_gemm.py @@ -82,8 +82,6 @@ def _build_inputs( is_nvfp4 = mode == "w4a4-nvfp4" if mode == "bf16": - # Native BF16: no quantization, no scale factors, no alpha. The kernel - # consumes the bf16 source directly; x/w double as the golden source. assert k % 64 == 0, f"k={k} must be divisible by 64 for bf16" x_bf16 = torch.randn(m, k, dtype=torch.bfloat16, device=dev) w_bf16 = torch.randn(n, k, dtype=torch.bfloat16, device=dev) @@ -302,8 +300,6 @@ def run_scenario(cfg: dict) -> None: os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) - # Bytes per operand element for the bandwidth metric: FP8 = 1, FP4 = 0.5, - # BF16 = 2. if mode == "bf16": dtype_bytes = 2 dtype_str = "bf16" diff --git a/benchmark/kernel/gemm/scenarios/grouped_gemm.py b/benchmark/kernel/gemm/scenarios/grouped_gemm.py index 3bbf86e..160419b 100644 --- a/benchmark/kernel/gemm/scenarios/grouped_gemm.py +++ b/benchmark/kernel/gemm/scenarios/grouped_gemm.py @@ -100,8 +100,6 @@ def _make_grouped_tensors(num_experts: int, max_m: int, n: int, k: int, mode: st is_nvfp4 = mode == "w4a4-nvfp4" if mode == "bf16": - # Native BF16: no quantization, no scale factors, no alpha. x/w double - # as the golden source (returned as x_bf16 / w_bf16). assert k % 64 == 0, f"k={k} must be divisible by 64 for bf16" x_bf16 = torch.randn(m, k, dtype=torch.bfloat16, device=dev) w_bf16_stacked = torch.randn( diff --git a/ci/baselines/gemm/batch_bf16.json b/ci/baselines/gemm/batch_bf16.json index b1a4265..2b41687 100644 --- a/ci/baselines/gemm/batch_bf16.json +++ b/ci/baselines/gemm/batch_bf16.json @@ -130,4 +130,4 @@ "median_us": 170.431 } ] -} \ No newline at end of file +} diff --git a/ci/baselines/gemm/dense_bf16.json b/ci/baselines/gemm/dense_bf16.json index 175700f..29c19a8 100644 --- a/ci/baselines/gemm/dense_bf16.json +++ b/ci/baselines/gemm/dense_bf16.json @@ -144,4 +144,4 @@ "median_us": 335.369 } ] -} \ No newline at end of file +} diff --git a/csrc/common/cpp_extensions.cc b/csrc/common/cpp_extensions.cc index 2cea984..61ebc4a 100644 --- a/csrc/common/cpp_extensions.cc +++ b/csrc/common/cpp_extensions.cc @@ -72,8 +72,8 @@ void DecoderAttention( void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, const std::optional& sfa, - const std::optional& sfb, - torch::Tensor& output, const std::optional& bias, + const std::optional& sfb, torch::Tensor& output, + const std::optional& bias, const std::optional& alpha, const int sm_count, const std::string& mode, const bool use_pdl, const EpilogueOp epilogue, @@ -81,13 +81,14 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, const double situ_beta, const std::optional situ_linear_beta); -void GroupMaskedGemm( - const torch::Tensor& input, const torch::Tensor& weight, - const std::optional& sfa, - const std::optional& sfb, const torch::Tensor& masked_m, - torch::Tensor& output, const std::optional& bias, - const std::optional& alpha, const int max_m_per_expert, - const int sm_count, const std::string& mode); +void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, + const std::optional& sfa, + const std::optional& sfb, + const torch::Tensor& masked_m, torch::Tensor& output, + const std::optional& bias, + const std::optional& alpha, + const int max_m_per_expert, const int sm_count, + const std::string& mode); void GroupContiguousGemm(const torch::Tensor& input, const torch::Tensor& weight, @@ -100,8 +101,8 @@ void GroupContiguousGemm(const torch::Tensor& input, void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, const std::optional& sfa, - const std::optional& sfb, - torch::Tensor& output, const std::optional& bias, + const std::optional& sfb, torch::Tensor& output, + const std::optional& bias, const std::optional& alpha, const int sm_count, const std::string& mode, const EpilogueOp epilogue, const std::optional& output_sf, diff --git a/csrc/kernel/gemm/batch_gemm.cu b/csrc/kernel/gemm/batch_gemm.cu index e0a06c7..e629ff5 100644 --- a/csrc/kernel/gemm/batch_gemm.cu +++ b/csrc/kernel/gemm/batch_gemm.cu @@ -38,8 +38,6 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, "input must be a 3D tensor of shape [B, M, K]"); TORCH_CHECK(weight.dim() == 3, "weight must be a 3D tensor of shape [B, N, K]"); - // mode="bf16" also takes the batch-major [B, M, N]; every other mode keeps - // the 2D contract the quantized store assumes. TORCH_CHECK(output.dim() == 2 || (output.dim() == 3 && mode == "bf16"), "output must be a 2D tensor of shape [M, B * N]"); @@ -49,9 +47,7 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, TORCH_CHECK(weight.size(0) == batches, "weight batch dim must match input batch dim, got ", weight.size(0)); - // Native BF16 also accepts the batch-major [B, M, N] output: contiguous - // per item, which writes faster at large B. Every other mode keeps the - // default [M, B * N] (the quantized store's TMA descriptor assumes it). + // Quantized stores require [M, B * N]; BF16 also accepts [B, M, N]. const bool bmn_out = output.dim() == 3; if (bmn_out) { TORCH_CHECK(output.is_contiguous(), @@ -89,7 +85,6 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.batch_out_bmn = bmn_out; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored. const int k = weight.size(2); TORCH_CHECK(input.size(2) == k, "input K must match weight K, got input K=", input.size(2), @@ -109,15 +104,14 @@ void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - LaunchCfg( - params, - {.m = m, - .n = n, - .k = k, - .m_grid = m * batches, - .sm_count = sm, - .has_bias = false}, - stream); + LaunchCfg(params, + {.m = m, + .n = n, + .k = k, + .m_grid = m * batches, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 batch GEMM requires sfa/sfb scale factors " diff --git a/csrc/kernel/gemm/dense_gemm.cu b/csrc/kernel/gemm/dense_gemm.cu index ea22090..0e7e054 100644 --- a/csrc/kernel/gemm/dense_gemm.cu +++ b/csrc/kernel/gemm/dense_gemm.cu @@ -73,7 +73,6 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, : 0.0f}; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored. TORCH_CHECK(input.dtype() == torch::kBFloat16, "bf16 dense GEMM: input must be bfloat16"); TORCH_CHECK(weight.dtype() == torch::kBFloat16, @@ -95,7 +94,6 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_c = nullptr; params.ptr_alpha = nullptr; - // Entry guards per tier (friendlier messages than the per-tile checks). if (m >= 128 && m < 4096) { CheckDivisible(m, 128, "BF16 GEMM mid M M"); CheckDivisible(n, 32, "BF16 GEMM mid M N"); @@ -105,15 +103,14 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, CheckDivisible(m, 64, "BF16 GEMM SwapAB M"); CheckDivisible(k, 64, "BF16 GEMM SwapAB K"); } - LaunchCfg( - params, - {.m = m, - .n = n, - .k = k, - .m_grid = m, - .sm_count = sm, - .has_bias = false}, - stream); + LaunchCfg(params, + {.m = m, + .n = n, + .k = k, + .m_grid = m, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 dense GEMM requires sfa/sfb scale factors " diff --git a/csrc/kernel/gemm/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index b6f84d2..f28e0ec 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -52,7 +52,6 @@ class CollectiveEpilogue { using CopyOpT2R = typename KernelTraits::CopyOpT2R; using CopyOpT2R_Sub = typename KernelTraits::CopyOpT2R_Sub; using OverlapComputeTile = typename KernelTraits::OverlapComputeTile; - // One epilogue compute tile spans the whole per-CTA M. static_assert(cute::size<0>(EpilogueTile{}) == cute::size<0>(EpiComputeTile{})); // Bias uses plain TMA (no 2SM multicast); each CTA loads its own copy. @@ -95,7 +94,6 @@ class CollectiveEpilogue { int rows_per_batch = 0; SituCoef situ{}; int64_t gate_ld = 0; - // Batch D layout: false = [M, B * N] (default), true = [B, M, N]. bool batch_out_bmn = false; // Stream-K fp32 partial workspace: [slot][CtaShape_M][KBlockN]; null // when stream-K is off. @@ -139,8 +137,6 @@ class CollectiveEpilogue { const bool batch = KernelTraits::KernelType == KernelMode::Batch; const int64_t q_n = n / KAccColsPerOut; const int64_t rows = batch ? args.rows_per_batch : m; - // Batch rows are B * N apart in the default layout, N when the caller - // asked for [B, M, N]. const int64_t d_ld = batch ? (args.batch_out_bmn ? q_n : num_experts * q_n) : q_n; cute::TmaDescriptor d_desc{}; @@ -275,9 +271,8 @@ class CollectiveEpilogue { return 0; } } - // Shift from the stacked-row D pointer to the tile's D. The default Batch - // layout moves batch b's rows to row 0, columns b * N; [B, M, N] keeps - // the stacked row. + // Default Batch remaps stacked rows to batch columns; + // [B, M, N] needs no shift. CUTLASS_DEVICE static int64_t d_shift( Params const& p, TileScheduler const& scheduler, TileRows const& rows) { @@ -285,7 +280,7 @@ class CollectiveEpilogue { const int64_t shift = batch_col0(p, scheduler) - (int64_t)rows.lo * p.d_ld; if constexpr (KernelTraits::KIsBF16) { - return p.batch_out_bmn ? 0 : shift; // only BF16 takes it + return p.batch_out_bmn ? 0 : shift; } else { return shift; } @@ -293,7 +288,6 @@ class CollectiveEpilogue { return 0; } } - // Per-expert alpha of the current tile; 1 when the traits carry none. CUTLASS_DEVICE static float tile_alpha( SharedStorage const& shared_storage, TileScheduler const& scheduler) { @@ -750,7 +744,6 @@ class CollectiveEpilogue { } } - // KStreamK: tail-only stream-K instantiation (BF16 only). template CUTLASS_DEVICE void epilogue(Params const& epilogue_params, AccumulatorPipeline& acc_pipeline, @@ -800,13 +793,9 @@ class CollectiveEpilogue { constexpr int kN = decltype(cute::size(thr_rd_sub))::value; static_assert(decltype(cute::size(tiled_t2r_sub))::value == cutlass::NumThreadsPerWarpGroup); - // The raw unit load assumes N in TMEM columns (32dp, 4x1); BF16 - // tiles also use the 16dp (64-row CTA) and 2SM "2x2" layouts, so - // they load through the partitioned tiled copy instead. + // BF16 uses partitioned T2R for 16dp and 2SM 2x2 layouts. constexpr bool kPartitionedLoad = KernelTraits::KIsBF16; - // BF16 tiles never straddle a batch (the host requires whole - // tiles), so they clip against the stacked D; a per-batch bound - // keeps the batch range live across the store loop and spills. + // BF16 tiles cannot cross batches; clip against whole D. constexpr bool kClipWholeD = KernelTraits::KIsBF16; cute::Tensor thr_tacc_src_sub = tiled_t2r_sub.get_slice(tx).partition_S(acc_sub_tile); @@ -845,12 +834,12 @@ class CollectiveEpilogue { shared_storage.tensor_sC(), OverlapComputeTile{})); cute::Tensor thr_rC_sub = cute::make_tensor(cute::shape(thr_rd_sub)); - const TileRows whole_d{ - 0, out_m, 0, - out_m % (SwapAB ? KernelTraits::KBlockN - : KernelTraits::KBlockM) == - 0}; - const auto clip_rows = [&](const TileRows& rows) -> const TileRows& { + const TileRows whole_d{0, out_m, 0, + out_m % (SwapAB ? KernelTraits::KBlockN + : KernelTraits::KBlockM) == + 0}; + const auto clip_rows = + [&](const TileRows& rows) -> const TileRows& { if constexpr (kClipWholeD) { return whole_d; } else { @@ -858,9 +847,7 @@ class CollectiveEpilogue { } }; - // Stream-K partials go to a compact per-CTA [CtaShape_M][KBlockN] - // slot, through the D store's thread layout. Built once: building - // it per sub-tile spills. Empty when !KStreamK. + // Compact per-CTA FP32 partials use D's thread layout. constexpr int kPartialM = cute::size<0>(CtaShape_MNK{}); constexpr int kPartialN = cute::size<1>(CtaShape_MNK{}); auto partial_store = [&]() { @@ -875,7 +862,8 @@ class CollectiveEpilogue { tiled_p, thr_p.retile_S(thr_racc_sub), thr_p.partition_D(cute::flat_divide( cute::make_tensor( - cute::make_gmem_ptr(epilogue_params.ptr_partial), + cute::make_gmem_ptr( + epilogue_params.ptr_partial), cute::make_layout( cute::make_shape(cute::Int{}, cute::Int{}), @@ -898,9 +886,6 @@ class CollectiveEpilogue { } int buf_i = 0; - // Quantized D: one UE8M0 scale per kGroup columns, e4m3 data via - // the SMEM stage and TMA (direct stores for rows above the box), - // then the row's scale word. const auto store_quant = [&](const __nv_bfloat162* vals, const TileRows& rows, int64_t row, bool row_ok, int64_t bcol0, int col0, @@ -937,11 +922,10 @@ class CollectiveEpilogue { } continue; } - uint8_t* buf = - stage + buf_i * KernelTraits::KEpiBufBytes; + uint8_t* buf = stage + buf_i * KernelTraits::KEpiBufBytes; *reinterpret_cast(buf + st_off + st_x) = lo; - *reinterpret_cast(buf + st_off + - (st_x ^ KVec)) = hi; + *reinterpret_cast(buf + st_off + (st_x ^ KVec)) = + hi; cutlass::arch::fence_view_async_shared(); if (issuer) { cute::tma_store_wait<0>(); @@ -962,8 +946,8 @@ class CollectiveEpilogue { if (row_ok) { *reinterpret_cast( epilogue_params.ptr_sfd + - sf_offset(epilogue_params, rows, row, - bcol0 + col0)) = sf_word; + sf_offset(epilogue_params, rows, row, bcol0 + col0)) = + sf_word; } }; @@ -1085,9 +1069,7 @@ class CollectiveEpilogue { } } else { const int sub_idx = wg * kUnits + u; - // The last N tile overhangs N (unaligned-SFB pair - // tiles, BF16 N-tails); a sub-tile is all in or all - // out because N is a multiple of the sub-tile width. + // N alignment makes each sub-tile wholly in or out. if constexpr ((KernelTraits::IsSfbUnaligned && !SwapAB) || KernelTraits::KEpiNeedsNPredicate) { @@ -1097,17 +1079,16 @@ class CollectiveEpilogue { return; } } - // Stream-K tail chunk: store the raw fp32 - // accumulator; the reduce kernel sums and casts. + // FP32 partials are summed before casting. if constexpr (KStreamK) { if (partial_slot >= 0) { auto dst_p = cute::get<2>(partial_store); dst_p.data() = dst_p.data() + partial_off; - cute::copy(cute::get<0>(partial_store), - cute::get<1>(partial_store), - dst_p((cute::_, cute::_), cute::_, - cute::_, cute::Int<0>{}, - sub_idx)); + cute::copy( + cute::get<0>(partial_store), + cute::get<1>(partial_store), + dst_p((cute::_, cute::_), cute::_, cute::_, + cute::Int<0>{}, sub_idx)); return; } } diff --git a/csrc/kernel/gemm/gemm_dispatch.cuh b/csrc/kernel/gemm/gemm_dispatch.cuh index cea77a7..e6d06b8 100644 --- a/csrc/kernel/gemm/gemm_dispatch.cuh +++ b/csrc/kernel/gemm/gemm_dispatch.cuh @@ -357,12 +357,8 @@ inline int PickTile(const TileSpec* tiles, int count, MmaKind kind, // Dispatch using TileLauncher = void (*)(GemmParams&, const GemmShape&, cudaStream_t); -// Candidates is any type exposing `static constexpr tiles`; every kind -// resolves through CandidateTiles (gemm_tile.cuh). -// Divisibility contract of a selected tile: the output M/N tile multiples -// (N relaxes to %64 for predicated tails and %32 for non-power-of-2 widths), -// K a KBlockK multiple. SwapAB swaps the roles: KBlockM tiles the weight -// (output N), KBlockN the activation (output M). +// Predicated N tails require 64/32 alignment. +// SwapAB exchanges the output M/N divisibility rules. inline void CheckBF16TileShape(const char* what, const TileSpec& t, int m, int n, int k) { const int n_mod = @@ -420,8 +416,6 @@ inline bool GemmTraceEnabled() { return on; } -// BF16 picks from its rule ladder instead of the cost model; defined with the -// ladder below. namespace bf16 { int PickBf16Tile(KernelMode mode, const GemmShape& shape); } // namespace bf16 @@ -454,33 +448,24 @@ void LaunchCfg(GemmParams& params, GemmShape shape, cudaStream_t stream) { kTileLaunchers[pick](params, shape, stream); } -// =========================================================================== -// BF16 dispatch. Rule-based rather than cost-model based: the ladder below -// encodes measured launch-shape bands (pair-UMMA gates, wave-fill judgements, -// K-tile depth gates). A selector returns an index into the per-mode tile -// tables in gemm_tile.cuh, or -1 when no tile supports the shape; -// PickBf16Tile feeds that index to the shared LaunchCfg. -// =========================================================================== +// BF16 dispatch uses empirically tuned shape and wave-fill thresholds. namespace bf16 { -// KBlockK of every BF16 tile. +// K quantum used by the ladder's depth gates. inline constexpr int kBlockK = 64; -// Deep-pipeline tiles (14/18 stages) only pay off from this many K-tiles. +// Tuned K-tile minimum for deep pipelines. inline constexpr int kDeepPipelineMinKTiles = 32; // The 64x96 / 128x64-pair deep tiles need at least this many K-tiles. inline constexpr int kMidMDeepMinKTiles = 54; -// 256x128 re-reads A twice as often as 256x256; beyond this many K-tiles the -// re-read outweighs any wave-packing gain. +// Tuned K-tile cap for 256x128 A rereads. inline constexpr int kNarrowPairMaxKTiles = 64; -// A 64-row tile has no multicast, so every extra N-tile re-reads A; cap the -// re-read volume (k_tiles * n_tiles) before stepping down to one. +// Tuned A-reread cap: k_tiles * n_tiles for 64-row tiles. inline constexpr int kRereadsCap = 2048; -// True if the deep (14/18-stage) pipeline variant pays off at this K. inline bool UseDeepPipeline(int k) { return k / kBlockK >= kDeepPipelineMinKTiles; } @@ -490,8 +475,7 @@ inline int64_t Count128x64PairCtas(int m, int n) { return 2 * int64_t(CeilDiv(m, 128)) * CeilDiv(n, 64); } -// For m < 128: a plain (non-SwapAB) 64-row tile beats SwapAB when even -// SwapAB's smallest tile leaves SMs idle. +// Avoid SwapAB when its finest grid underfills. inline bool SkipSwapForThinM(int m, int n, int k, int sm_count) { if (m % 64 != 0 || k % 64 != 0) { return false; @@ -514,8 +498,7 @@ inline bool FillsLastWaveBetter(int64_t coarse_ctas, int64_t fine_ctas, return fine_ctas * coarse_waves > coarse_ctas * fine_waves; } -// 256x128 instead of 256x256 when K is short, the grid is not too deep, and -// 256x128 keeps more SMs busy. +// Tuned grid cap for the narrow pair tile: four waves. inline bool UseNarrowPairTile(int n, int k, int64_t coarse_ctas, int64_t fine_ctas, int64_t target) { return (n % 128 == 0) && (k / kBlockK <= kNarrowPairMaxKTiles) && @@ -523,8 +506,6 @@ inline bool UseNarrowPairTile(int n, int k, int64_t coarse_ctas, FillsLastWaveBetter(coarse_ctas, fine_ctas, target); } -// ---- Small-N (N <= 128) tiles ---------------------------------------------- - inline constexpr int kSmallNMaxN = 128; inline constexpr int kSmallNAlignN = 64; @@ -541,8 +522,7 @@ inline bool FillsOneWave(int64_t ctas, int64_t target) { return ctas <= target && 2 * ctas > target; } -// N fits one tile, so all CTAs come from splitting M: pick the largest tile -// whose CTA count lands in (0.5, 1.0] of one wave. +// Tuned one-wave band: 0.5 < CTAs / target <= 1. inline SmallNTile PickSmallNTile(int m, int n, int64_t target) { if (n > kSmallNMaxN || n % kSmallNAlignN != 0) { return SmallNTile::kNone; @@ -563,8 +543,6 @@ inline SmallNTile PickSmallNTile(int m, int n, int64_t target) { return SmallNTile::kNone; } -// ---- Dense ----------------------------------------------------------------- -// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum DenseTile : int { kPair256x256 = Bf16TileId(kBF16_256x256_pair), kPair256x256P7 = Bf16TileId(kBF16_256x256_pair_p7), @@ -610,7 +588,6 @@ inline int SelectLargeMTile(int m, int n, int k, int target) { break; } const int64_t tiles_256 = int64_t(CeilDiv(m, 256)) * CeilDiv(n, 256); - // 256x128 (deeper pipeline) when it keeps more SMs busy on a short K. if (UseNarrowPairTile(n, k, 2 * tiles_256, 2 * int64_t(CeilDiv(m, 256)) * CeilDiv(n, 128), target)) { @@ -622,15 +599,12 @@ inline int SelectLargeMTile(int m, int n, int k, int target) { if (n % 128 == 0) { return kPair256x128; } - // n % 128 != 0 (e.g. 1600): predicated-tail 128-wide tile, else 256x64. if (n % 64 == 0) { return kPair256x128Ntail; } return kPair256x64; } -// Halve the 128-row tile's N (256 -> 128 -> 64 -> 32) while the current width -// leaves SMs idle. Returns the chosen N width. inline int Pick128xNWidth(int m, int n, int target) { auto tiles = [&](int tm, int tn) { return CeilDiv(m, tm) * CeilDiv(n, tn); @@ -652,8 +626,6 @@ inline int Pick128xNWidth(int m, int n, int target) { return pick == 0 ? 256 : (pick == 1 ? 128 : (pick == 2 ? 64 : 32)); } -// 256xN pair-UMMA ladder for m % 256 == 0; returns -1 when its gates reject -// the shape and the 128xN ladder should decide instead. inline int SelectPair256xNTile(int m, int n, int k, int target) { if (n % 64 != 0) { return -1; @@ -661,27 +633,23 @@ inline int SelectPair256xNTile(int m, int n, int k, int target) { auto pair_ctas = [&](int tn) { return int64_t(m / 256) * CeilDiv(n, tn) * 2; }; - // Halve N only while the grid is under one wave, and never from >= half - // a wave into more than one wave. + // Do not cross one wave from a grid above half a wave. auto step_ok = [&](int coarse, int fine) { return pair_ctas(coarse) < target && !(pair_ctas(fine) > target && 2 * pair_ctas(coarse) > target); }; int pair_tn = (n % 256 == 0) ? 256 : ((n % 128 == 0) ? 128 : 64); - // n % 128 != 0 (e.g. 1600): the 128-wide predicated-tail tile instead of - // 64 if it fills at least half a wave. + // Predicated 128-wide tails require at least half a wave. bool pair_n_tail = false; if (pair_tn == 64 && (n % 128 != 0) && 2 * pair_ctas(128) >= target) { pair_tn = 128; pair_n_tail = true; } - // Also 128 when the narrow-pair rule says so (multi-wave). if (pair_tn == 256 && (n % 128 == 0) && (step_ok(256, 128) || UseNarrowPairTile(n, k, pair_ctas(256), pair_ctas(128), target))) { pair_tn = 128; } - // 192 if it fits one wave and keeps more SMs busy than both 256 and 128. if (pair_tn != 64 && (n % 32 == 0) && pair_ctas(192) <= target && FillsLastWaveBetter(pair_ctas(256), pair_ctas(192), target) && FillsLastWaveBetter(pair_ctas(128), pair_ctas(192), target)) { @@ -693,15 +661,13 @@ inline int SelectPair256xNTile(int m, int n, int k, int target) { } const int64_t cta_count = pair_ctas(pair_tn); const int k_tiles = k / kBlockK; - // Prologue amortization: enough K-tiles to fill three pipelines, or a - // full wave of tiles. + // Tuned gate: 3*stages or a full wave. const int stages = pair_tn == 256 ? 6 : (pair_tn == 192 ? 8 : (pair_tn == 128 ? 8 : 10)); const bool amortizes = k_tiles >= 3 * stages || cta_count >= target; // The 64-wide arm needs at least 0.8 of a wave. const bool narrow_arm_fills = pair_tn != 64 || 5 * cta_count >= 4 * target; - // If n % 128 != 0 forced 256x64 and it spills past one wave, defer to the - // 64x96 / 64x224 tiles below. + // Defer oversubscribed 256x64 to the 64-row fill tiles. const int ctas96 = CeilDiv(m, 64) * CeilDiv(n, 96); const int ctas224 = CeilDiv(m, 64) * CeilDiv(n, 224); const bool narrow_arm_overshoots = @@ -719,8 +685,7 @@ inline int SelectPair256xNTile(int m, int n, int k, int target) { case 128: return pair_n_tail ? kPair256x128P9Ntail : kPair256x128P9; default: - // With <= 32 K-tiles the 1-CTA 128x64 tile (same CTA count) is - // faster than the 256x64 pair. + // Tuned: prefer 1-CTA 128x64 for <=32 K-tiles. return k_tiles <= 32 ? kM128x64 : kPair256x64; } } @@ -731,15 +696,11 @@ inline int SelectMidMTile(int m, int n, int k, int target) { return -1; } - // ---- 64-row tiles (64x64 / 64x32) ---------------------------------- - // Smaller tiles add CTAs but, with no multicast, every extra N-tile - // re-reads A; use them only on a one-wave grid with bounded re-reads. if (m % 64 == 0 && n % 64 == 0) { const int tiles64 = CeilDiv(m, 64) * CeilDiv(n, 64); const int64_t rereads = int64_t(k / kBlockK) * CeilDiv(n, 64); if (tiles64 <= target && rereads <= kRereadsCap) { - // 1 epilogue warp group: required for 64x32, and it skips the - // inter-warp-group barrier on 64x64. + // 64x32 requires one epilogue warp group. if (2 * tiles64 <= target && n % 32 == 0) { return UseDeepPipeline(k) ? kM64x32_1wgP18 : kM64x32_1wg; } @@ -747,7 +708,6 @@ inline int SelectMidMTile(int m, int n, int k, int target) { } } - // ---- 256xN pair-UMMA tiles (m % 256 == 0) -------------------------- if (m % 256 == 0) { const int pair = SelectPair256xNTile(m, n, k, target); if (pair >= 0) { @@ -755,19 +715,14 @@ inline int SelectMidMTile(int m, int n, int k, int target) { } } - // ---- 128xN width ---------------------------------------------------- const int pick_tn = Pick128xNWidth(m, n, target); auto tiles = [&](int tm, int tn) { return CeilDiv(m, tm) * CeilDiv(n, tn); }; - // ---- 64x96 / 64x224 fill tiles -------------------------------------- - // Power-of-2 N widths can miss one wave entirely (n=7168: 112 or 224 CTAs - // on 152 SMs); 96/224 land in between. const int ctas96 = CeilDiv(m, 64) * CeilDiv(n, 96); const int ctas224 = CeilDiv(m, 64) * CeilDiv(n, 224); - // The incumbent is the 128xN choice, adjusted for the 64x128 wave fix - // below when that applies. + // Baseline CTA count includes the 64x128 fallback below. const int incumbent_ctas = (n % 128 == 0 && tiles(128, pick_tn) > target && tiles(64, 128) <= target) ? tiles(64, 128) @@ -776,8 +731,7 @@ inline int SelectMidMTile(int m, int n, int k, int target) { return c <= target && 2 * c > target && (incumbent_ctas > target || c > incumbent_ctas); }; - // The 256x64 pair arm deferred here in favour of 64x96; take it even - // though it exceeds one wave. + // A deferred pair arm may use 64x96 beyond one wave. const bool pair_deferred_to_96 = (m % 256 == 0) && (n % 64 == 0) && (n % 128 != 0) && (int64_t(m / 256) * CeilDiv(n, 64) * 2 > target); @@ -790,14 +744,11 @@ inline int SelectMidMTile(int m, int n, int k, int target) { return kM64x224; } - // ---- 64x128 when the 128xN tile spills past one wave ----------------- if ((m % 64 == 0) && (n % 128 == 0) && tiles(128, pick_tn) > target && tiles(64, 128) <= target) { return kM64x128; } - // ---- 128x64 pair, 18 stages ------------------------------------------ - // One wave with enough K-tiles, or the 128x128 incumbent (only 4 stages). if ((m % 128 == 0) && (n % 128 == 0)) { const int64_t pair_ctas = Count128x64PairCtas(m, n); const int k_tiles = k / kBlockK; @@ -805,7 +756,7 @@ inline int SelectMidMTile(int m, int n, int k, int target) { const bool deep_enough = k_tiles >= kMidMDeepMinKTiles; const bool shallow_incumbent = (pick_tn == 128); if ((one_wave && deep_enough) || shallow_incumbent) { - // With <= 64 K-tiles the 64x64 1WG deep tile is faster. + // Tuned: prefer deep 64x64 1WG for <=64 K-tiles. if (one_wave && deep_enough && k_tiles <= 64 && (m % 64 == 0) && (n % 64 == 0)) { return kM64x64_1wgP14; @@ -814,15 +765,12 @@ inline int SelectMidMTile(int m, int n, int k, int target) { } } - // ---- 128xN base ------------------------------------------------------ return pick_tn == 256 ? kM128x256 : (pick_tn == 128 ? kM128x128 : (pick_tn == 64 ? kM128x64 : kM128x32)); } -// m < 128 without SwapAB (SkipSwapForThinM): KBlockM=64 tiles give ceil(n/32) -// CTAs; 64x32 if it fits one wave, else 64x64. inline int SelectThinMTile(int m, int n, int k, int target) { const int nt32 = CeilDiv(n, 32); const int mt = CeilDiv(m, 64); @@ -832,8 +780,6 @@ inline int SelectThinMTile(int m, int n, int k, int target) { return UseDeepPipeline(k) ? kM64x64_1wgP14 : kM64x64_1wg; } -// m < 128 with SwapAB: the weight (N x K) becomes the MMA's A (M-dim 128), -// the activation (M x K) the MMA's B (N-dim). inline int SelectSwapABTile(int m, int n, int k, int target) { if (n % 128 != 0 || m % 64 != 0 || k % 64 != 0) { return -1; @@ -847,7 +793,6 @@ inline int SelectSwapABTile(int m, int n, int k, int target) { if ((n % 256 == 0) && tiles128 > 2 * target) { return kSwap256x64Pair; } - // KBlockN=32 if that still fits one wave. if (CeilDiv(n, 128) * CeilDiv(m, 32) <= target) { return kSwap128x32; } @@ -869,9 +814,6 @@ inline int SelectBF16Cfg(int m, int n, int k, int sm_count) { return SelectSwapABTile(m, n, k, target); } -// ---- Grouped / batch ------------------------------------------------------- - -// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum ContiguousTile : int { kContPair256x256 = Bf16TileId(kBF16_256x256_pair_p7), kContPair256x128 = Bf16TileId(kBF16_256x128_pair_p9), @@ -890,24 +832,20 @@ inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { return kContPair256x256; } if (m >= 128) { - // M stays 128 (the 1-CTA MMA requires M == 128); step finer on N - // only while the coarser tile underfills the grid. + // The 1-CTA MMA keeps M=128; refine N only. const int target = sm_count > 0 ? sm_count : GetSmCount(); auto tiles = [&](int tm, int tn) { return CeilDiv(m, tm) * CeilDiv(n, tn); }; - // 2-CTA pair-UMMA first: weight TMA-multicast across the pair. Each - // cluster spans 2 SMs, so require clusters * 2 >= target. + // Pair-UMMA weight multicast spans two SMs per cluster. const int clusters = CeilDiv(m, 256) * CeilDiv(n, 256); if (m % 256 == 0 && n % 256 == 0 && k % 64 == 0 && clusters * 2 >= target) { - // 256x128 frees a deeper pipeline; it pays only when 256x256 is - // lightly oversubscribed (<= ~2 waves). + // Tuned 256x128 cluster-count cap: 2 * target. const bool square_like = (n % 128 == 0) && (clusters <= 2 * target); return square_like ? kContPair256x128 : kContPair256x256; } - // 128x64 only on a <= 1-wave fit: halving N doubles the M*K panel - // reloads (costly on DRAM-bound mid-M). + // Halving N doubles A-panel reloads; keep 128x64 within one wave. if (tiles(128, 256) < target && (n % 128 == 0)) { if (tiles(128, 64) <= target && (n % 64 == 0)) { return kContM128x64; @@ -919,7 +857,6 @@ inline int SelectBF16ContiguousCfg(int m, int n, int k, int sm_count) { return kContSwap128x64; } -// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum MaskedTile : int { kMaskM128x256 = Bf16TileId(kBF16_128x256_ovlp16), kMaskSwap128x64 = Bf16TileId(kBF16_128x64_swap), @@ -932,8 +869,7 @@ static_assert(kMaskPair256x128 >= 0 && kMaskPair256x128 < static_cast(kBF16Tiles.size()), "BF16 masked tile id outside kBF16Tiles"); -// Masked pads every expert to max_m_per_expert, so the grid scales with -// num_experts * ceil(max_m / tm) * ceil(n / tn). +// mm is padded rows per expert. inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, int sm_count) { if (mm >= 4096) { @@ -950,8 +886,7 @@ inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, const bool square_like = (n % 128 == 0) && (clusters <= 2 * target); return square_like ? kMaskPair256x128 : kMaskPair256x256; } - // Keep 128x256 (best B-reuse) unless it underfills the grid; a - // blanket 128x128 preference regresses oversubscribed mid-M. + // Keep wide N for reuse unless the grid underfills. if (tiles(128, 256) < target && (n % 128 == 0)) { if (tiles(128, 64) <= target && (n % 64 == 0)) { return kMaskM128x64; @@ -963,7 +898,6 @@ inline int SelectBF16MaskedCfg(int num_experts, int mm, int n, int k, return kMaskSwap128x64; } -// Ids into kBF16Tiles (gemm_tile.cuh), derived from the tile itself. enum BatchTile : int { kBatchPair256x256 = Bf16TileId(kBF16_256x256_pair), kBatchM128x256 = Bf16TileId(kBF16_128x256_ovlp16), @@ -973,7 +907,7 @@ static_assert(kBatchSwap128x64 >= 0 && kBatchSwap128x64 < static_cast(kBF16Tiles.size()), "BF16 batch tile id outside kBF16Tiles"); -// Pure alignment ladder (no runtime SM reasoning); m is one item's rows. +// m is one batch item's row count. inline int SelectBF16BatchCfg(int m, int n, int k) { if (m % 256 == 0 && n % 256 == 0) { return kBatchPair256x256; @@ -987,7 +921,6 @@ inline int SelectBF16BatchCfg(int m, int n, int k) { return -1; } -// BF16 picks from the rule ladder above, one table per mode. inline int PickBf16Tile(KernelMode mode, const GemmShape& shape) { switch (mode) { case KernelMode::Dense: diff --git a/csrc/kernel/gemm/gemm_kernel.cuh b/csrc/kernel/gemm/gemm_kernel.cuh index fdba905..b98f54f 100644 --- a/csrc/kernel/gemm/gemm_kernel.cuh +++ b/csrc/kernel/gemm/gemm_kernel.cuh @@ -85,8 +85,6 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) bool is_load_ab_warp = (warp_idx == KernelTraits::KLoadABWarpId); - // Prefetch TMA descriptors: the AB warp handles A and B (plus SFA/SFB for - // block-scaled modes). if (is_load_ab_warp && lane_predicate) { cute::prefetch_tma_descriptor( mainloop_params.tma_load_A.get_tma_descriptor()); @@ -199,10 +197,9 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) BiasPipeline bias_pipeline(shared_storage.bias_pipeline, bias_pipeline_params); - // TMEM allocation, issued right before the barrier that waits on it. + // The CTA/cluster sync below publishes tmem_base_ptr. TmemAllocator tmem_allocator{}; if (warp_idx == KernelTraits::KMmaWarpId) { - // Right-sized (KTmemColumns), not the full 512 columns. tmem_allocator.allocate(KernelTraits::KTmemColumns, &shared_storage.tmem_base_ptr); } @@ -228,14 +225,12 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) } TmemStorage tmem_storage = main_loop.init_tmem_tensors(); - // The load warp skips set_tmem_offsets and the first tmem_base_ptr read - // (where alloc latency surfaces). + // The AB load warp does not use TMEM. if (!is_load_ab_warp) { main_loop.set_tmem_offsets(tmem_storage, shared_storage.tmem_base_ptr); } if (is_load_ab_warp) { - // Prologue warps release registers to the pool. if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } @@ -244,9 +239,8 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) if constexpr (KernelTraits::KUsePdl) { pdl_trigger(); } - } else if (warp_idx == KernelTraits::KMmaWarpId && - is_mma_leader_cta) { // mma - // MMA warp uses TMEM for accumulators, needs few GP registers. + } else if (warp_idx == KernelTraits::KMmaWarpId && is_mma_leader_cta) { + // MMA accumulators live in TMEM. if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } @@ -259,15 +253,13 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } - // Guarded so the rewriter (static_asserts IsSfbRowShift) is not - // instantiated elsewhere. + // Compile-time guard for the rewriter's IsSfbRowShift assertion. if constexpr (KernelTraits::IsSfbRowShift) { main_loop.sfb_shift_rows( mainloop_params, shared_storage, scheduler, warp_idx - KernelTraits::KSfbTransposeWarpId); } } else if (warp_idx <= KernelTraits::KEpilogueWarpEndId) { - // Epilogue warps need the most registers. if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_alloc< KernelTraits::KNumRegsEpilogue>(); @@ -283,7 +275,6 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) epilogue_loop.load_c(epilogue_params, bias_pipeline, shared_storage, scheduler); } else { - // Any non-participant warp releases registers. if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } @@ -297,7 +288,6 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) __syncthreads(); } - // Deallocate TMEM (must match the allocated column count). if (warp_idx == KernelTraits::KMmaWarpId) { tmem_allocator.release_allocation_lock(); tmem_allocator.free(shared_storage.tmem_base_ptr, @@ -446,15 +436,13 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, "gemm_impl requires M to be divisible by KBlockM=", KernelTraits::KBlockM, ", got ", params.m); if constexpr (KernelTraits::IsSfbUnaligned) { - // Unpacked 224-pair tiles load whole 128-row SF atoms, so n - // must tile at 128. + // 224-pair SF loads require whole 128-row atoms. TORCH_CHECK(params.n % 128 == 0 && params.n >= 384, "gemm_impl requires N to be a multiple of 128 and " ">= 384 for KBlockN=", KernelTraits::KBlockN, ", got ", params.n); } else if constexpr (KernelTraits::KEpiNeedsNPredicate) { - // Non-power-of-2 KBlockN (96/112/224) need not divide n; the - // overhang is predicated per sub-tile. + // Predicated N tails require KSubTileN alignment. TORCH_CHECK(params.n % KernelTraits::KSubTileN == 0, "gemm_impl with KBlockN=", KernelTraits::KBlockN, " predicates the N overhang per ", @@ -479,7 +467,6 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, } } -// Kernel-pointer launch: the caller picks data-parallel or stream-K. template void LaunchGemmKernel(void const* kernel_ptr, dim3 dim_grid, dim3 dim_cluster, @@ -517,9 +504,8 @@ void gemm_impl_body(GemmParams& params, const int sm_count, using ClusterShape_MNK = typename KernelTraits::ClusterShape_MNK; static constexpr int KCTAsPerCluster = cute::size(ClusterShape_MNK{}); - // Same SM-count resolution as the dispatch-site tile heuristics. const int raw_sm_count = sm_count > 0 ? sm_count : GetSmCount(); - // Round down to a multiple of KCTAsPerCluster. + // Launch only full clusters. const int runtime_sm_count = (raw_sm_count / KCTAsPerCluster) * KCTAsPerCluster; int M = params.m; @@ -555,8 +541,7 @@ void gemm_impl_body(GemmParams& params, const int sm_count, cute::Layout layout_C = cute::make_layout( cute::make_shape(M, N), cute::make_stride(N, cute::Int<1>{})); - // Scale tensors cover whole 128-row SfAtom atoms even for M < 128 rows - // (unused for BF16). + // SF layouts require 128-row padding, even for M < 128. const int M_sf = AlignSfM(M); typename KernelTraits::LayoutSFA layout_SFA = SwapAB ? KernelTraits::Sm1xxBlkScaledConfig::tile_atom_to_shape_SFA( @@ -584,7 +569,6 @@ void gemm_impl_body(GemmParams& params, const int sm_count, int scheduler_m = SwapAB ? N : M; int scheduler_n = SwapAB ? M : N; - // The scheduler sizes the stream-K tail against the persistent grid. const int num_clusters_planned = runtime_sm_count / KCTAsPerCluster; const int k_tiles_planned = cutlass::ceil_div(K, cute::size<2>(typename KernelTraits::TileShape{})); @@ -593,8 +577,6 @@ void gemm_impl_body(GemmParams& params, const int sm_count, params.masked_m, params.expert_ids, num_clusters_planned, k_tiles_planned); - // Stream-K fp32 workspace, allocated only when a tail was split: - // rem * splits * KNumCTA slots of CtaShape_M x KBlockN. static constexpr int KPartM = KernelTraits::KBlockM / KernelTraits::KNumCTA; static constexpr int KPartN = KernelTraits::KBlockN; at::Tensor streamk_ws; @@ -621,8 +603,7 @@ void gemm_impl_body(GemmParams& params, const int sm_count, params.situ, params.gate_ld, params.batch_out_bmn, streamk_active ? streamk_ws.data_ptr() : nullptr}); - // The launch reserves the whole SMEM capacity, which also keeps multiple - // concurrent streams from fitting two blocks on one SM. + // Reserve full SMEM capacity to enforce one CTA per SM. static_assert(sizeof(typename KernelTraits::SharedStorage) <= cutlass::arch::sm100_smem_capacity_bytes, "SMEM usage exceeded capacity"); @@ -632,9 +613,6 @@ void gemm_impl_body(GemmParams& params, const int sm_count, int smem_size = cutlass::arch::sm100_smem_capacity_bytes; - // Two instantiations picked by pointer: data-parallel and fused - // stream-K; `if constexpr` keeps other traits from instantiating a dead - // stream-K copy. auto* kernel_ptr_dp = &gemm_kernel; void const* kernel_ptr = (void const*)kernel_ptr_dp; @@ -663,7 +641,6 @@ void gemm_impl_body(GemmParams& params, const int sm_count, } if (streamk_active) { - // Reduce tail partials into D; whole tiles were already stored. launch_stream_k_reduce( static_cast(params.ptr_d), streamk_ws.data_ptr(), scheduler_params.streamk_tail_base, scheduler_params.streamk_rem, diff --git a/csrc/kernel/gemm/gemm_tile.cuh b/csrc/kernel/gemm/gemm_tile.cuh index 2d95593..e3cf17c 100644 --- a/csrc/kernel/gemm/gemm_tile.cuh +++ b/csrc/kernel/gemm/gemm_tile.cuh @@ -27,26 +27,8 @@ namespace halops { inline constexpr int kSwapEpiChunk = 2 * kMatRows; inline constexpr int kSfbRowShiftAlign = 64; -// Dense GEMM tile parameters. -// -// BM, BN, BK KBlockM/N/K; for SwapAB, BM is the weight's M and BN the -// activation extent. -// PST, EST prologue (mainloop) / epilogue pipeline depth. -// CM, CN cluster shape; IsPairUmma = CM*CN > 1. -// OVLP KTmemOverlapCols. -// REG KNumRegsEpilogue; 160 is the Reg160 occupancy variant. -// SWZ UseTileSwizzle. -// FENCE SkipTmemFence. -// SWAP, FP4 SwapAB, KIsFP4. -// SFVS KSfVecSize: 16 = NVFP4, 32 = MXFP4. -// ALPHA, BIAS HasAlpha, AddBias. -// MODE KernelType. -// OP KEpiOp (epilogue op). -// EWGO KEpilogueWarpGroupsOverride; 0 = auto (SwapAB ? 1 : 2). -// NTAIL KForceEpiNPredicate (predicated store on power-of-2 N). -// BF16 KIsBF16 (native BF16 GEMM, no scale factors). -// ATOM CTAs per MMA atom: 0 = auto (CM*CN > 1 ? 2 : 1), 1 = 1SM, -// 2 = 2x1SM. +// SwapAB: BM tiles weights, BN activations. +// SFVS: 16 = NVFP4, 32 = MXFP4. template 1 implies pair-UMMA). + // ATOM=0 selects 2 CTAs for a multi-CTA cluster, otherwise 1. static constexpr int KAtomCtas = ATOM == 0 ? ((CM * CN) > 1 ? 2 : 1) : ATOM; static constexpr bool IsPairUmma = KAtomCtas == 2; static constexpr int KEpilogueWarpGroupsOverride = EWGO; @@ -98,12 +80,12 @@ struct TileSpec { bool bias = false; // AddBias // Dispatch policy, not kernel parameters. - bool dense_only = false; // only tuned/allowed for the dense launcher - bool batch = false; // a dense_only tile also tuned for batch - bool searchable = true; // may the cost model pick it? + bool dense_only = false; // only tuned/allowed for the dense launcher + bool batch = false; // a dense_only tile also tuned for batch + bool searchable = true; // may the cost model pick it? int quant_stages = 0; - int epi_warp_groups = 0; // KEpilogueWarpGroupsOverride; 0 = auto - bool force_ntail = false; // KForceEpiNPredicate (predicated N-tail store) + int epi_warp_groups = 0; // 0 = auto + bool force_ntail = false; // Predicate stores even for power-of-2 N tiles. constexpr bool pair() const { return cluster_m * cluster_n > 1; } // Activation-tile rows/cols; SwapAB swaps the two MMA dimensions. @@ -193,8 +175,7 @@ struct MmaTraits { using OperandA = Operand; using OperandB = Operand; using Output = cutlass::bfloat16_t; - // Placeholder only: BF16 has no scale factors and never dereferences - // the SF pointer. + // Unused placeholder: BF16 has no scale factors. using Scale = cutlass::float_ue8m0_t; static constexpr bool kFp4 = false; static constexpr int kSfVecSize = 16; @@ -209,8 +190,7 @@ using MakeTile = S.cluster_m, S.cluster_n, S.tmem_overlap, S.epi_regs, S.swizzle, S.skip_fence, S.swap_ab, MmaTraits::kFp4, MmaTraits::kSfVecSize, MmaTraits::kHasAlpha, S.bias, - Mode, Op, S.epi_warp_groups, S.force_ntail, - Kind == MmaKind::BF16>; + Mode, Op, S.epi_warp_groups, S.force_ntail, Kind == MmaKind::BF16>; // Fp8 constexpr TileSpec kFp8_128x256 = {.block_m = 128, @@ -474,17 +454,7 @@ struct CandidateTiles { static constexpr const auto& tiles = kW4a8Tiles; }; -// =========================================================================== -// BF16 tiles — no block-scale, no alpha. KBlockK=64 gives the same per-stage -// A/B smem as FP8@KBlockK=128 and there is no SFA/SFB smem, so stage counts -// can mirror the FP8 configs. epi_warp_groups=1 marks the 1-epilogue-warp- -// group layouts (narrow tiles, 2SM "2x2" TMEM layout); force_ntail marks the -// predicated N-tail store (N only has to divide 64, or 32 for non-power-of-2 -// widths). dense_only stays false on every BF16 tile: the mode selectors in -// gemm_dispatch.cuh pick the tile, so the flag is never consulted. -// -// One tile table serves all four modes; ids are derived from it below. -// --------------------------------------------------------------------------- +// BF16 KBlockK=64 matches FP8 KBlockK=128 A/B SMEM per stage. constexpr TileSpec kBF16_256x256_pair = {.block_m = 256, .block_n = 256, .block_k = 64, @@ -597,7 +567,6 @@ constexpr TileSpec kBF16_128x64x128_swap = {.block_m = 128, .main_stages = 4, .swap_ab = true}; -// Grouped/batch tiles: deeper / TMEM-overlapped variants of the dense shapes. constexpr TileSpec kBF16_128x256_ovlp16 = {.block_m = 128, .block_n = 256, .block_k = 64, @@ -611,10 +580,6 @@ constexpr TileSpec kBF16_128x64_ovlp16 = {.block_m = 128, .main_stages = 8, .tmem_overlap = 16}; -// Every BF16 launch draws from this one table; the per-mode ids in -// gemm_dispatch.cuh index it directly, so a tile several modes share appears -// once. Order is free apart from keeping the dense block first, which is what -// the historical id order was. inline constexpr std::array kBF16Tiles = { kBF16_256x256_pair, kBF16_256x256_pair_p7, kBF16_256x128_pair, kBF16_256x128_pair_ntail, @@ -628,15 +593,10 @@ inline constexpr std::array kBF16Tiles = { kBF16_64x64_1wg_p14, kBF16_64x32_1wg, kBF16_64x32_1wg_p18, kBF16_128x64_swap, kBF16_128x32_swap, kBF16_256x64_swap_pair, - kBF16_128x64x128_swap, - // Grouped/batch: deeper or TMEM-overlapped variants of the dense shapes. - kBF16_128x256_ovlp16, kBF16_128x128_p6, - kBF16_128x64_ovlp16, + kBF16_128x64x128_swap, kBF16_128x256_ovlp16, + kBF16_128x128_p6, kBF16_128x64_ovlp16, }; -// Index of a tile in kBF16Tiles. The per-mode ids in gemm_dispatch.cuh are -// derived from it, so an id cannot point at the wrong tile and a tile missing -// from the table fails to compile. consteval int Bf16TileId(const TileSpec& t) { for (std::size_t i = 0; i < kBF16Tiles.size(); ++i) { if (kBF16Tiles[i] == t) { @@ -650,11 +610,6 @@ template <> struct CandidateTiles { static constexpr const auto& tiles = kBF16Tiles; }; -// --------------------------------------------------------------------------- -// Field-lock asserts: guard the designated-initializer tables above against -// drift. These tables replaced hand-written GemmTile structs; the locks pin -// every kernel-facing constant a table entry must produce. -// --------------------------------------------------------------------------- template diff --git a/csrc/kernel/gemm/group_contiguous_gemm.cu b/csrc/kernel/gemm/group_contiguous_gemm.cu index 99e314d..d64110c 100644 --- a/csrc/kernel/gemm/group_contiguous_gemm.cu +++ b/csrc/kernel/gemm/group_contiguous_gemm.cu @@ -66,7 +66,6 @@ void GroupContiguousGemm(const torch::Tensor& input, params.use_pdl = true; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored. const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -83,15 +82,14 @@ void GroupContiguousGemm(const torch::Tensor& input, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - LaunchCfg( - params, - {.m = m, - .n = n, - .k = k, - .m_grid = m, - .sm_count = sm, - .has_bias = false}, - stream); + LaunchCfg(params, + {.m = m, + .n = n, + .k = k, + .m_grid = m, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 contiguous grouped GEMM requires sfa/sfb " diff --git a/csrc/kernel/gemm/group_masked_gemm.cu b/csrc/kernel/gemm/group_masked_gemm.cu index 8db2ac1..7dfdb76 100644 --- a/csrc/kernel/gemm/group_masked_gemm.cu +++ b/csrc/kernel/gemm/group_masked_gemm.cu @@ -75,7 +75,6 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.use_pdl = true; if (mode == "bf16") { - // Native BF16: sfa/sfb/bias/alpha are ignored. const int k = weight.size(2); TORCH_CHECK(input.size(1) == k, "input K must match weight K, got input K=", input.size(1), @@ -92,15 +91,14 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, params.ptr_sfa = nullptr; params.ptr_sfb = nullptr; params.ptr_alpha = nullptr; - LaunchCfg( - params, - {.m = max_m_per_expert, - .n = n, - .k = k, - .m_grid = m, - .sm_count = sm, - .has_bias = false}, - stream); + LaunchCfg(params, + {.m = max_m_per_expert, + .n = n, + .k = k, + .m_grid = m, + .sm_count = sm, + .has_bias = false}, + stream); } else if (mode == "w8a8-mxfp8") { TORCH_CHECK(sfa.has_value() && sfb.has_value(), "w8a8-mxfp8 masked grouped GEMM requires sfa/sfb scale " diff --git a/csrc/kernel/gemm/kernel_traits.cuh b/csrc/kernel/gemm/kernel_traits.cuh index 569eaff..d28fd76 100644 --- a/csrc/kernel/gemm/kernel_traits.cuh +++ b/csrc/kernel/gemm/kernel_traits.cuh @@ -98,14 +98,11 @@ struct GemmKernelTraits { static constexpr bool KNarrowA = NarrowA_ && (KDenseW8A8MXFP8 || (KernelType == KernelMode::Batch && !AddBias)) && - !KIsBF16 && - !SwapAB && !IsPairUmma && !KernelConfig_::KIsFP4 && KBlockK == 128; + !KIsBF16 && !SwapAB && !IsPairUmma && !KernelConfig_::KIsFP4 && + KBlockK == 128; static constexpr bool KUsePdl = UsePdl_; static constexpr int KMmaK = KIsFP4 ? 64 : (KIsBF16 ? 16 : 32); - // Tail-only stream-K: only the BF16 dense no-bias no-alpha epilogue can - // deposit an fp32 partial. SwapAB is excluded (the tail fold-back assumes - // non-swap traversal; m=64 n=19584 k=1024 gave 121% rel error), as are - // N-predicated tiles (their partial slot leaves holes the reduce sums). + // Stream-K partials require non-SwapAB traversal and unpredicated N. static constexpr bool KSupportsStreamK = KernelType == KernelMode::Dense && KIsBF16 && !AddBias && !HasAlpha && !SwapAB && (KBlockN % 128 == 0 || KBlockN == 32 || KBlockN == 64) && @@ -134,8 +131,6 @@ struct GemmKernelTraits { static constexpr int KQuantAccCols = KAccColsPerOut * mxfp8::kGroup; // Epilogue warp groups split N: 1 for bf16 SwapAB (small N) and for a // quantized tile narrower than two quant groups, 2 otherwise. - // KEpilogueWarpGroupsOverride forces 1, e.g. to make KBlockN=32 legal at - // CtaM==64 (KEpiComputeN=32 meets the T2R atom floor). static constexpr int KEpilogueWarpGroupCount = KernelConfig_::KEpilogueWarpGroupsOverride != 0 ? KernelConfig_::KEpilogueWarpGroupsOverride @@ -153,12 +148,11 @@ struct GemmKernelTraits { static constexpr int KNumRegsEpilogue = KernelConfig_::KNumRegsEpilogue; static constexpr bool SkipTmemFence = KernelConfig_::SkipTmemFence; static constexpr int KNumRegsOther = 88; - // setmaxnreg redistribution (208 + 88 split) for BF16 needs enough warps; - // without it ptxas gives every warp one flat budget (54-87 regs), starving - // the epilogue. Quantized configs keep the warp-group-count rule. + // Redistribute BF16 registers to avoid a flat per-warp epilogue budget. static constexpr bool KRedistributeRegs = - KIsBF16 ? (KNumWarp >= 8 && (!SwapAB || KernelType == KernelMode::Dense)) - : KEpilogueWarpGroupCount != 1; + KIsBF16 + ? (KNumWarp >= 8 && (!SwapAB || KernelType == KernelMode::Dense)) + : KEpilogueWarpGroupCount != 1; using TileShape = cute::Shape, cute::Int, cute::Int>; @@ -170,29 +164,21 @@ struct GemmKernelTraits { static constexpr int KEpiComputeN = KBlockN / KEpilogueWarpGroupCount; using EpiComputeTile = cute::Shape, cute::Int>; - // Overlap TMEM loads use 16-wide sub-tiles (the TMEM load atom width); - // KTmemOverlapCols need not divide KEpiComputeN, only both be multiples of - // 16. Without overlap this is EpiComputeTile. - // - // Non-power-of-2 KBlockN (96/112/224) has no T2R atom for KEpiComputeN and - // splits into 32-wide sub-tiles (16 gives only 8 fp32/thread, too few for - // SM100_STORE_256bit). Not legal on the 2SM "2x2" layout: a 32-wide slice - // straddles the N-half boundary and writes wrong elements. + // Overlap widths need 16-column alignment; + // fallback sub-tiles must fill a 256-bit store. static constexpr bool KEpiNIsSingleAtom = (KEpiComputeN == 16 || KEpiComputeN == 32 || KEpiComputeN == 64 || KEpiComputeN == 128); - // Quantized dtypes keep main's rule: 16-wide unless the per-WG width has - // its own atom (8 included). static constexpr bool KEpiComputeNHasAtom = KEpiNIsSingleAtom || KEpiComputeN == 8; static constexpr int KSubTileN = - KIsBF16 ? (KTmemOverlapCols != 0 - ? 16 - : (KEpiNIsSingleAtom - ? KEpiComputeN - : (KEpiComputeN % 32 == 0 ? 32 : 16))) - : ((KTmemOverlapCols == 0 && KEpiComputeNHasAtom) ? KEpiComputeN - : 16); + KIsBF16 + ? (KTmemOverlapCols != 0 + ? 16 + : (KEpiNIsSingleAtom ? KEpiComputeN + : (KEpiComputeN % 32 == 0 ? 32 : 16))) + : ((KTmemOverlapCols == 0 && KEpiComputeNHasAtom) ? KEpiComputeN + : 16); static_assert(!KIsBF16 || KEpiNIsSingleAtom || !(KNumCTA == 2 && KBlockM == 128), "a non-power-of-2 KBlockN cannot use the 2SM 128-row \"2x2\" " @@ -211,10 +197,9 @@ struct GemmKernelTraits { (KTmemOverlapCols == 16 || KTmemOverlapCols == 32 || KTmemOverlapCols == 64 || KTmemOverlapCols == 128); - // TMEM budget: tcgen05.alloc takes a power-of-2 column count in [32, 512]; - // accumulators need KEpilogueStages * KBlockN. Only BF16 without overlap - // right-sizes; block-scaled dtypes also hold SFA/SFB in TMEM and overlap - // shares columns between stages. + // tcgen05.alloc requires power-of-two columns in [32, 512]. + // Keep the full allocation for SF storage or overlapping accumulator + // stages. static constexpr int KAccTmemColumns = KEpilogueStages * KBlockN; static constexpr int round_up_tmem_columns(int v) { int r = 32; @@ -228,27 +213,17 @@ struct GemmKernelTraits { ? round_up_tmem_columns(KAccTmemColumns) : 512; - // T2R atom selection depends on per-CTA M and N. NNdp is the number of - // datapath lanes an atom addresses: a 1SM 64-row accumulator fills only 16 - // lanes per subpartition, so it needs a 16dp atom (32dp fails - // "Non-injective Layout") with the N repeat halved. Both use 128 threads. static constexpr int KEpiCtaM = KBlockM / KNumCTA; static_assert(KEpiCtaM == 64 || KEpiCtaM == 128, "UMMA accumulators support 64 or 128 rows per CTA only " "(mma_traits_sm100.hpp:502)."); - // 16dp32b8x is too narrow for the 256-bit store, so a 64-row CTA tile - // needs KEpiComputeN >= 32. static_assert(KEpiCtaM == 128 || KEpiComputeN >= 32, "CtaM==64 needs a 16dp TMEM load atom, whose N repeat count " "is half the 32dp one; KEpiComputeN < 32 would land on " "16dp32b8x, which cannot fill SM100_STORE_256bit."); - // Accumulator layout being read: - // 1CTA M=64 -> half subpartition, 16 lanes, N in columns (16dp atom); - // 2CTA M=128 -> "2x2", second N half on datapaths 64-127, N/2 columns; - // 2CTA M=256 -> "4x1", all 128 lanes, N in columns. - // "2x2" needs a 32dp atom and a full-KBlockN epilogue tile - // (KEpilogueWarpGroupsOverride=1), else warps 2/3 address outside it. + // 1CTA M=64: 16dp; 2CTA M=128: 2x2, N/2 columns. + // 2CTA M=256: 4x1, N columns. static constexpr bool KIs2SmHalfM = (KNumCTA == 2) && (KEpiCtaM == 64); static constexpr int KEpiTmemDp = (KNumCTA == 1 && KEpiCtaM == 64) ? 16 : 32; @@ -259,9 +234,6 @@ struct GemmKernelTraits { "KEpilogueWarpGroupsOverride = 1) or warps 2/3 address " "outside the tile and the output is silently wrong."); - // T2R op for EpiComputeTile N (and CtaM). `Nx` is the column count; a - // mismatched width moves the wrong columns, so every reachable width needs - // its own arm. The 16dp series (CtaM=64) uses half-width atoms. using CopyOpT2R = cute::conditional_t< KEpiTmemDp == 16, cute::conditional_t< @@ -271,7 +243,6 @@ struct GemmKernelTraits { cute::SM100_TMEM_LOAD_16dp32b16x>>, cute::conditional_t< KIs2SmHalfM, - // 2SM "2x2": N/2 columns are used, so the repeat is halved. cute::conditional_t< KEpiComputeN == 128, cute::SM100_TMEM_LOAD_32dp32b64x, cute::conditional_t>>>>>; - // Overlap: 16-wide sub-tile load (16 fp32/thread fills SM100_STORE_256bit; - // 8x is too few). No overlap: width-matched CopyOpT2R. CtaM=64 halves the - // repeat. Columns per sub-tile: N/2 on 16dp and "2x2", N on 4x1. + // 16dp and 2x2 use N/2 TMEM columns per sub-tile. static constexpr int KSubTileTmemCols = (KEpiTmemDp == 16 || KIs2SmHalfM) ? KSubTileN / 2 : KSubTileN; - // Width-matched atom for one sub-tile; only for non-power-of-2 KBlockN. using CopyOpT2R_SubWide = cute::conditional_t< KEpiTmemDp == 16, cute::conditional_t< @@ -322,8 +290,6 @@ struct GemmKernelTraits { cute::SM100_TMEM_LOAD_16dp32b8x, cute::SM100_TMEM_LOAD_32dp32b16x>>>; - // Each chain above ends in the narrowest atom; make_tmem_copy replicates - // it over the tile, which is only correct when the atom width divides it. static_assert(!KIsBF16 || KEpiComputeN % KSubTileN == 0, "the epilogue sub-tile loop must cover KEpiComputeN exactly"); static_assert(!KIsBF16 || KEpiNIsSingleAtom || KTmemOverlapCols != 0 || @@ -333,9 +299,7 @@ struct GemmKernelTraits { "the tile when the tile's TMEM column count is a multiple of " "16. Widen the table before using such a width."); - // Non-power-of-2 KBlockN may overhang N, so the store is predicated at - // KSubTileN granularity (n must be a multiple of it). KForceEpiNPredicate - // forces this for a power-of-2 KBlockN (N=1600 on a 128-wide tile). + // N predication is per KSubTileN; N must be a multiple of it. static constexpr bool KEpiNeedsNPredicate = KIsBF16 && (((KBlockN & (KBlockN - 1)) != 0) || KernelConfig_::KForceEpiNPredicate); @@ -343,10 +307,6 @@ struct GemmKernelTraits { // Scale-factor vector size: 16 = NVFP4, 32 = MXFP4. static constexpr int KSFVecSize = KernelConfig_::KSfVecSize; - // Real MMA atom used for the actual A@B computation. - // FP4 -> SM100_MMA_MXF4_SS / _2x1SM_SS (block-scaled, has TypeSF) - // FP8 -> SM100_MMA_MXF8F6F4_SS / _2x1SM_SS (block-scaled, has TypeSF) - // BF16 -> SM100_MMA_F16BF16_SS / _2x1SM_SS (NON block-scaled, no SF) using MMA_T = cute::conditional_t< KIsBF16, cute::conditional_t< @@ -388,11 +348,8 @@ struct GemmKernelTraits { "Static cluster shape used: TileShape should be " "evenly divided by TiledMma"); - // F16BF16 has no SF members, so BF16 derives the SF types below from a - // dummy MXF4 MMA; they are unused at runtime. MXF4 (SFVecSize=16) rather - // than MXF8F6F4 (32): 64/16 = 4 matches the SfAtom's 4-in-K granularity. - // The dummy keeps a fixed SFTileShape so the block-scaled constraints - // (1-CTA M==128, KBlockK==64) do not leak into BF16 tiles. + // BF16 uses a type-only MXF4 SF atom: 64/16 matches the 4-in-K layout. + // A fixed dummy tile keeps block-scaled constraints out of BF16 tiles. static constexpr int KSFDummyM = KNumCTA == 1 ? 128 : 256; using SFTileShape = cute::conditional_t< KIsBF16, @@ -414,9 +371,7 @@ struct GemmKernelTraits { cute::conditional_t; - // Unaligned-N pair tiles (IsSfbUnaligned) load SFB as a run of 128-row - // atoms, so the SF MMA atom is 128 wide rather than round_up(N). BF16 - // never takes this arm. + // Unaligned-N SFB uses 128-row atoms, independent of the GEMM tile width. using MMA_SF_T = cute::conditional_t< KIsBF16 || SwapAB || KBlockN % 128 == 0, typename TiledMmaForSF::MMA_ScaleFactor, @@ -434,7 +389,6 @@ struct GemmKernelTraits { cute::Layout>, cute::Tile>; - // SF fragment types for the mainloop's TMEM SF tensors. using FrgTypeSFA = typename TiledMmaForSF::FrgTypeSFA; using FrgTypeSFB = typename TiledMmaForSF::FrgTypeSFB; @@ -444,7 +398,6 @@ struct GemmKernelTraits { cute::_1, cute::_1>; using CtaShape_MNK = decltype(cute::shape_div(TileShape{}, AtomThrShapeMNK{})); - // Per-CTA SFTileShape; equals CtaShape_MNK for FP8/FP4. using SFCtaShape_MNK = decltype(cute::shape_div(SFTileShape{}, AtomThrShapeMNK{})); @@ -455,10 +408,8 @@ struct GemmKernelTraits { static constexpr bool IsCtaNSmall = cute::size<1>(CtaShape_MNK{}) < Blk_MN{}; static constexpr int IsCtaN64 = cute::size<1>(CtaShape_MNK{}) == 64; - // A pair tile whose N is not a multiple of the 128-row SF atom (e.g. 224) - // starts at a 32-row-aligned offset inside an atom; SFB is then the - // covering run of whole atoms and the MMA's SFB address moves forward by - // that offset (one TMEM column holds 32 atom rows). BF16 skips this. + // Unaligned SFB uses a whole-atom load window and an offset MMA address. + // One TMEM column covers 32 SF rows. static constexpr bool IsSfbUnaligned = !KIsBF16 && !KIsFP4 && (!SwapAB || KernelConfig_::KSwapSfbRun) && KBlockN > 128 && KBlockN % 128 != 0; @@ -528,9 +479,6 @@ struct GemmKernelTraits { using SmemLayoutAtomSFA = decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFA(TiledMmaForSF{}, SFTileShape{})); - // Unaligned-N SFB loads KSfbAtoms whole atoms, so the SMEM atom covers - // CTA_N_SF rows instead of SFTileShape's N. Every other tile uses the - // SFTileShape form. using SmemLayoutAtomSFB = cute::conditional_t< IsSfbUnaligned, decltype(Sm1xxBlkScaledConfig::deduce_smem_layoutSFB( @@ -590,7 +538,6 @@ struct GemmKernelTraits { 128) cute::ArrayEngine> A; alignas( 128) cute::ArrayEngine> B; - // SFA/SFB SMEM: size 0 for BF16 (no scale factors). alignas(128) cute::ArrayEngine< TypeSF, KIsBF16 ? 0 : cute::cosize_v> SFA; alignas(128) cute::ArrayEngine< @@ -635,9 +582,8 @@ struct GemmKernelTraits { typename AccumulatorPipeline::SharedStorage; alignas(16) AccumulatorPipelineStorage accumulator; - // Pair-UMMA overlap: the peer's overlap WG must finish T2R before the - // leader issues the next UMMA, so it arrives on this cluster barrier - // (the leader's NamedBarrier cannot see it). + // The peer overlap WG must finish T2R before the next UMMA; + // the leader's NamedBarrier cannot synchronize it. alignas(8) typename cutlass::arch::ClusterBarrier::ValueType overlap_cluster_bar; @@ -647,9 +593,9 @@ struct GemmKernelTraits { sf_full[KSfFullStages]; }; - static constexpr bool KActRowTma = - KernelType == KernelMode::Batch && SwapAB && IsPairUmma && !KIsFP4 && - !KIsBF16; + static constexpr bool KActRowTma = KernelType == KernelMode::Batch && + SwapAB && IsPairUmma && !KIsFP4 && + !KIsBF16; static constexpr int KActRowAlign = std::gcd(KBlockN, mxfp8::kAtomRows); static constexpr int KCtaRows = KBlockM / KNumCTA; diff --git a/csrc/kernel/gemm/mainloop_fwd.cuh b/csrc/kernel/gemm/mainloop_fwd.cuh index ff1dfaa..c445ddf 100644 --- a/csrc/kernel/gemm/mainloop_fwd.cuh +++ b/csrc/kernel/gemm/mainloop_fwd.cuh @@ -28,7 +28,6 @@ struct CollectiveMainloop { using TiledMma = typename KernelTraits::TiledMma; using TiledMma_SF = typename KernelTraits::TiledMma_SF; using TiledMmaForSF = typename KernelTraits::TiledMmaForSF; - // BF16 (kind::f16) has no block-scale factors; SF paths compile out. static constexpr bool KIsBF16 = KernelTraits::KIsBF16; using AtomThrID = typename TiledMma::AtomThrID; using UtccpOp = cute::conditional_t(&desc, CU_TENSOR_MAP_DATA_TYPE_UINT8, ptr, - {static_cast(k), - static_cast(cute::size<0>(layout))}, - {static_cast(cute::stride<0>(layout))}, - {static_cast(KernelTraits::KBlockK), - static_cast(box_rows)}, - CU_TENSOR_MAP_SWIZZLE_128B, what); + EncodeTmaDesc<2>( + &desc, CU_TENSOR_MAP_DATA_TYPE_UINT8, ptr, + {static_cast(k), + static_cast(cute::size<0>(layout))}, + {static_cast(cute::stride<0>(layout))}, + {static_cast(KernelTraits::KBlockK), + static_cast(box_rows)}, + CU_TENSOR_MAP_SWIZZLE_128B, what); }; cute::TmaDescriptor a_run_desc{}; if constexpr (KernelTraits::KNarrowA) { const int rows = NarrowARows(args.m, args.num_experts); row_box_desc(a_run_desc, args.ptr_a, args.layout_A, - rows > 0 ? rows - : std::min(cute::size<0>(args.layout_A), - KernelTraits::KBlockM), + rows > 0 + ? rows + : std::min(cute::size<0>(args.layout_A), + KernelTraits::KBlockM), "narrow A"); } cute::TmaDescriptor act_row_desc{}; @@ -385,8 +385,8 @@ struct CollectiveMainloop { if constexpr (IsSfbUnaligned) { // tile_atom_to_shape_SFB orders atoms K-block first, then N. const uint64_t k_blks = cute::size<1, 1>(args.layout_SFB); - // Grouped modes lay the experts out after the N atoms, so they fold - // into the same run dimension (one stride per atom). + // Grouped modes lay the experts out after the N atoms, so they + // fold into the same run dimension (one stride per atom). const uint64_t n_atoms = static_cast( cute::ceil_div(cute::size<0>(args.layout_B), 128)); EncodeTmaDesc<3>( @@ -395,8 +395,8 @@ struct CollectiveMainloop { n_atoms * static_cast(SwapAB ? 1 : args.num_experts)}, {kSfbAtomBytes, k_blks * kSfbAtomBytes}, - {kSfbAtomBytes / 2, 1, KSfbAtoms}, CU_TENSOR_MAP_SWIZZLE_NONE, - "SFB atom run"); + {kSfbAtomBytes / 2, 1, KSfbAtoms}, + CU_TENSOR_MAP_SWIZZLE_NONE, "SFB atom run"); } return {args.layout_A, @@ -433,7 +433,6 @@ struct CollectiveMainloop { TileScheduler& scheduler) { bool select_thr = cute::elect_one_sync(); - // Unused: the per-work-item K range comes from the scheduler. [[maybe_unused]] uint32_t tile_num_k = cute::ceil_div(mainloop_params.k, cute::size<2>(TileShape{})); @@ -487,8 +486,7 @@ struct CollectiveMainloop { }(); cute::Tensor cta_sA = shared_storage.tensor_sA(); cute::Tensor cta_sB = shared_storage.tensor_sB(); - // Slice by the atom's thread coord, not the flat cluster rank: extra - // CTAs of a multi-CTA cluster would index past the atom layout. + // Use atom-local CTA rank, not flat cluster rank. cute::ThrMMA cta_mma = tiled_mma.get_slice( block_rank_in_cluster % cute::size(typename TiledMma::AtomThrID{})); @@ -584,9 +582,7 @@ struct CollectiveMainloop { block_rank_in_cluster % cute::size(typename TiledMma_SF::AtomThrID{})); - // SFTileShape and TiledMmaForSF must be used together: for BF16 they - // are dummy stand-ins, and mixing them with the real ones breaks - // tma_partition's mode-0 sizes. + // SF partitioning requires the matching dummy BF16 shape and MMA. cute::ThrMMA cta_mma_sfa = TiledMmaForSF{}.get_slice( block_rank_in_cluster % cute::size(typename TiledMmaForSF::AtomThrID{})); @@ -703,8 +699,7 @@ struct CollectiveMainloop { lo + KernelTraits::KBlockM - narrow_rows); narrow_smem_row = narrow_row - lo; } - // Stream-K: a work item may cover only a K-slice; producer and - // consumer take the range from the scheduler, so stages match. + // Producer and consumer must use the same scheduler K slice. const uint32_t k_lo = scheduler.k_begin(); const uint32_t k_hi = scheduler.k_end(); for (uint32_t k_tile_id = k_lo; k_tile_id < k_hi; ++k_tile_id) { @@ -713,7 +708,6 @@ struct CollectiveMainloop { mainloop_pipe_producer_state); prologue_stage_idx = mainloop_pipe_producer_state.index(); - // A, B (+ SFA, SFB unless BF16) TMA copies share one barrier. if (select_thr) { if constexpr (IsSfbRowShift) { cutlass::arch::ClusterTransactionBarrier:: @@ -759,14 +753,14 @@ struct CollectiveMainloop { prologue_stage_idx))); } if constexpr (!KIsBF16) { - cute::copy(mainloop_params.tma_load_SFA.with( - *tma_barrier, mcast_mask_sfa), - a_tile(tma_gSFA, m_idx, k_tile_id, expert_idx), - tma_sSFA(cute::_, - (cute::Int<0>{}, prologue_stage_idx))); + cute::copy( + mainloop_params.tma_load_SFA.with(*tma_barrier, + mcast_mask_sfa), + a_tile(tma_gSFA, m_idx, k_tile_id, expert_idx), + tma_sSFA(cute::_, + (cute::Int<0>{}, prologue_stage_idx))); } if constexpr (KIsBF16) { - // No scale factors. } else if constexpr (!IsSfbUnaligned) { cute::copy( mainloop_params.tma_load_SFB.with(*tma_barrier, @@ -873,13 +867,11 @@ struct CollectiveMainloop { TileScheduler& scheduler) { bool select_thr = cute::elect_one_sync(); - // Unused: the per-work-item K range comes from the scheduler. [[maybe_unused]] uint32_t tile_num_k = cute::ceil_div(mainloop_params.k, cute::size<2>(TileShape{})); uint32_t iter_k = KernelTraits::kItersK; int block_rank_in_cluster = cute::block_rank_in_cluster(); - // Same atom-rank rule as tma_loadAB_impl (see there). int cta_atom_rank = block_rank_in_cluster % cute::size(typename TiledMma::AtomThrID{}); @@ -933,9 +925,7 @@ struct CollectiveMainloop { AccumulatorPipelineState accumulator_pipe_producer_state = cutlass::make_producer_start_state(); - // KStreamK=false only: prefetch the next tile's accumulator stage and - // first k-stage right after the MMAs are issued, hiding producer - // latency. With stream-K the K ranges differ, so every k-tile waits. + // Stream-K disables next-tile prefetch because K ranges vary. [[maybe_unused]] bool next_tile_ready = false; while (scheduler.is_valid()) { @@ -979,13 +969,10 @@ struct CollectiveMainloop { tiled_mma.accumulate_ = cute::UMMA::ScaleOut::Zero; - // Stream-K: same K range the producer used (see tma_loadAB). const uint32_t k_lo = scheduler.k_begin(); const uint32_t k_hi = scheduler.k_end(); for (uint32_t k_tile_id = k_lo; k_tile_id < k_hi; ++k_tile_id) { prologue_stage_idx = mainloop_pipe_consumer_state.index(); - // Data-parallel: the prefetched first k-stage was already - // waited on. if constexpr (KStreamK) { mainloop_pipeline.consumer_wait( mainloop_pipe_consumer_state); @@ -995,7 +982,6 @@ struct CollectiveMainloop { mainloop_pipe_consumer_state); } } - // UTCCP copy of scale factors into TMEM (block-scaled only). if constexpr (!KIsBF16) { if (select_thr) { copy(tiled_copy_s2t_SFA, @@ -1014,8 +1000,6 @@ struct CollectiveMainloop { for (uint32_t k_block_id = 0; k_block_id < iter_k; ++k_block_id) { if constexpr (KIsBF16) { - // kind::f16 MMA: no scale factors, only the - // accumulate flag. gemm(tiled_mma, tile_rA(cute::_, cute::_, k_block_id, prologue_stage_idx), @@ -1051,8 +1035,6 @@ struct CollectiveMainloop { scheduler.advance(); if constexpr (!KStreamK) { - // Prefetch: acquire the next accumulator stage and wait on - // its first k-stage now. next_tile_ready = scheduler.is_valid(); if (next_tile_ready) { accumulator_pipeline.producer_acquire( diff --git a/csrc/kernel/gemm/stream_k_reduce.cuh b/csrc/kernel/gemm/stream_k_reduce.cuh index 25da308..b514039 100644 --- a/csrc/kernel/gemm/stream_k_reduce.cuh +++ b/csrc/kernel/gemm/stream_k_reduce.cuh @@ -18,13 +18,7 @@ #include -// Reduction pass for tail-only stream-K (see tile_scheduler.cuh). -// -// The first `tail_base` cluster-tiles are written straight to D; the remaining -// `rem` tiles are split into `splits` K-chunks, each depositing an fp32 partial -// to partial[((t * splits + s) * num_cta + v)][cta_m][block_n]. This kernel -// sums the per-tile partials into D. Cost scales with rem*splits only; a shared -// buffer with atomicAdd serializes on the address. +// FP32 partials: [tail tile][split][CTA][CtaM][BlockN]. template __global__ void stream_k_reduce_kernel(TypeD* __restrict__ ptr_d, float const* __restrict__ ptr_partial, @@ -36,9 +30,7 @@ __global__ void stream_k_reduce_kernel(TypeD* __restrict__ ptr_d, return; } - // Unflatten: [t][v][cta_m][block_n], 4 columns per thread (scalar stores - // are issue-bound). Slots are CtaM*BlockN floats, so float4 loads and the - // 4x TypeD store stay aligned. + // Unflatten [tail tile][CTA][row][column / 4] for aligned vector accesses. constexpr int kVec = 4; constexpr int kColVecs = BlockN / kVec; const int col = static_cast(idx % kColVecs) * kVec; diff --git a/csrc/kernel/gemm/tile_scheduler.cuh b/csrc/kernel/gemm/tile_scheduler.cuh index 375ab37..d5bb654 100644 --- a/csrc/kernel/gemm/tile_scheduler.cuh +++ b/csrc/kernel/gemm/tile_scheduler.cuh @@ -57,11 +57,8 @@ struct TileScheduler { static constexpr int kExpertClusterRows = kExpertTileSize * kExpertClusterTiles; - // Preamble specializations: the constructor runs in every warp and is - // pure per-CTA preamble. Without swizzle only the compact path is - // reachable (S > 1 implies UseTileSwizzle). + // Without swizzle, S=1 and only the compact path is reachable. static constexpr bool kAlwaysCompact = !UseTileSwizzle; - // cluster == CTA: use gridDim/blockIdx directly. static constexpr bool kIsSingleCtaCluster = (KernelTraits::KNumCTA == 1) && (cute::size(ClusterShape_MNK{}) == 1); @@ -76,14 +73,12 @@ struct TileScheduler { int expert_ctm; // per-expert cluster-tiles in M int expert_ctn; // per-expert cluster-tiles in N int total_tiles; // num_logical_experts * tiles_per_expert - // Host-precomputed fast divmod (avoid runtime division). cutlass::FastDivmod divmod_tiles; // ÷ tiles_per_expert cutlass::FastDivmod divmod_ss; // ÷ S*S cutlass::FastDivmod divmod_blocks; // ÷ blocks_fast cutlass::FastDivmod divmod_s; // ÷ S - // Compact scheduling flag; the rest of the state is derived on device. - bool use_compact_sched; // true for Masked with the linear path (S=1) + bool use_compact_sched; int batch_own_tiles; cutlass::FastDivmod divmod_batch_period; cutlass::FastDivmod divmod_slow_tiles; @@ -91,21 +86,14 @@ struct TileScheduler { int batch_valid_tiles; float batch_per_tile; - // Linear-path traversal orientation (Naive only; see - // to_underlying_arguments). - // false → N-fast (tile_id ÷ expert_ctn): consecutive tiles sweep N. - // true → M-fast (tile_id ÷ expert_ctm): consecutive tiles sweep M. + // M-fast override for linear, non-SwapAB dense tiles. bool traverse_m_fast; // Contiguous-range tile assignment instead of strided (Batch SwapAB). bool chunked_assign; - // Tail-only stream-K (streamk_rem == 0 disables). Over C clusters and - // W tiles, the first (W/C)*C tiles stay data-parallel; each remaining - // tile is split into streamk_splits K-chunks, so the makespan drops - // from ceil(W/C) to W/C + 1/splits and only the tail needs fp32 - // partials. Work-id space: [0, tail_base) whole tiles, then - // (tail tile, K-chunk) pairs. + // Work IDs: [0, tail_base) whole tiles, then (tail tile, K-chunk). + // streamk_rem == 0 disables splitting. int streamk_tail_base; int streamk_rem; int streamk_splits; @@ -173,10 +161,8 @@ struct TileScheduler { int tiles_per_expert = blocks_m * blocks_n * S * S; int total_tiles = num_logical_experts * tiles_per_expert; - // The operand indexed by the fast dimension stays L2-resident, so - // keep the smaller one: N-fast for N <= M, M-fast for M < N. Naive - // non-SwapAB picks M-fast when m < n (N-fast re-reads a large B every - // wave). HALOPS_TRAVERSE_MFAST=0 forces N-fast. + // Prefer the smaller operand in L2; HALOPS_TRAVERSE_MFAST=0 forces + // N-fast. bool traverse_m_fast = false; if constexpr (KernelTraits::KernelType == KernelMode::Dense && !SwapAB) { @@ -198,24 +184,18 @@ struct TileScheduler { cutlass::FastDivmod divmod_blocks(divmod_blocks_divisor); cutlass::FastDivmod divmod_s(S); - // Tail-only stream-K (see Params). splits must divide k_tiles. int streamk_tail_base = total_tiles; int streamk_rem = 0; int streamk_splits = 1; - // KSupportsStreamK limits this to BF16 dense without bias/alpha or - // SwapAB. if constexpr (KernelTraits::KSupportsStreamK) { - // Default on; rejected shapes keep streamk_rem == 0 (no - // workspace, no reduce launch). HALOPS_STREAMK=0 forces off. + // HALOPS_STREAMK=0 disables stream-K. static const bool streamk_enabled = [] { const char* e = std::getenv("HALOPS_STREAMK"); return e == nullptr || e[0] != '0'; }(); const int C = num_clusters; - // Underfill extension: total_tiles > 0 also admits whole == 0 - // (thin M), where every tile is split to occupy more SMs. p_cap - // keeps near-full grids at p = 1 and bounds the workspace at C - // slots. HALOPS_STREAMK_FILL=0 restores the tail-only gate. + // Split underfilled grids too; HALOPS_STREAMK_FILL=0 keeps + // tail-only splitting. static const bool streamk_fill = [] { const char* e = std::getenv("HALOPS_STREAMK_FILL"); return e == nullptr || e[0] != '0'; @@ -225,14 +205,11 @@ struct TileScheduler { if (streamk_enabled && S == 1 && C > 0 && k_tiles > 0 && size_ok) { const int whole = total_tiles / C; const int rem = total_tiles - whole * C; - // Split only when the remainder idles >= 5% of SM-time - // (break-even for the partial-tile reduction). + // Tuned break-even: >=5% idle SM-time. const bool worth_it = rem > 0 && (C - rem) * 20 >= (whole + 1) * C; if (worth_it) { - // Largest p <= min(C / rem, 8) dividing k_tiles; the - // overhead is fixed, not per split. HALOPS_STREAMK_P - // overrides the cap. + // Tuned split cap: 8; HALOPS_STREAMK_P overrides. int p_cap = C / rem < 8 ? C / rem : 8; static const int p_forced = [] { const char* e = std::getenv("HALOPS_STREAMK_P"); @@ -249,8 +226,7 @@ struct TileScheduler { } } if (p >= 2 && (whole > 0 || p >= 4)) { - // With whole == 0 only p >= 4 repays the fp32 - // workspace round-trip and reduce launch. + // Tuned underfill minimum: 4 splits. streamk_tail_base = whole * C; streamk_rem = rem; @@ -261,8 +237,6 @@ struct TileScheduler { } } - // Compact scheduling for Masked/Contiguous with S=1; all state is - // computed on device (no D2H copy, no host masked_m access). bool use_compact_sched = false; if (S == 1) { use_compact_sched = true; @@ -294,11 +268,8 @@ struct TileScheduler { kExpertClusterRows) : 0.f; - // Chunked assignment (Batch SwapAB): SwapAB numbering keeps one - // item's N segments consecutive, but the persistent stride spreads - // them across CTAs, so the shared activation's L2 reuse becomes a - // race. Give CTA i the range [i*chunk, (i+1)*chunk). Only when - // expert_ctm > 1. HALOPS_BATCH_CHUNK=0 restores the stride. + // Keep each batch item's segments together for activation reuse. + // HALOPS_BATCH_CHUNK=0 restores strided assignment. bool chunked_assign = false; if constexpr (KernelTraits::KernelType == KernelMode::Batch && SwapAB && KernelTraits::KIsBF16) { @@ -348,8 +319,6 @@ struct TileScheduler { uint32_t cluster_num_; // stride = number of clusters uint32_t current_tile_id_; // current position in global tile space - // Chunked assignment: step 1, range ends at tile_end_; otherwise step is - // cluster_num_ and the range ends at the total tile count. uint32_t advance_step_; uint32_t tile_end_; @@ -377,12 +346,10 @@ struct TileScheduler { bool traverse_m_fast_; bool chunked_assign_; - // Tail-only stream-K state (see Params). streamk_rem_ == 0 disables. uint32_t streamk_tail_base_; uint32_t streamk_rem_; uint32_t streamk_splits_; uint32_t k_tiles_; - // Set per work item by find_next_valid_tile(). uint32_t k_begin_; uint32_t k_end_; int partial_slot_; // -1 writes straight to D, else an fp32 ws slot @@ -474,7 +441,6 @@ struct TileScheduler { streamk_rem_(params.streamk_rem), streamk_splits_(params.streamk_splits), k_tiles_(params.k_tiles) { - // Only the non-compact bounds check reads these. if constexpr (!kAlwaysCompact) { tile_num_m_ = ceil_div(params.m, size<0>(TileShape{})); tile_num_n_ = ceil_div(params.n, size<1>(TileShape{})); @@ -482,10 +448,8 @@ struct TileScheduler { int cluster_idx; if constexpr (kIsSingleCtaCluster) { - // cluster == CTA: use gridDim/blockIdx directly. cluster_num_ = gridDim.x * gridDim.y; cluster_idx = blockIdx.x * gridDim.y + blockIdx.y; - // Single-CTA cluster: block_rank 0, flat coord (0,0,0). cluster_m_tiles_ = kClusterMTiles; cluster_n_tiles_ = kClusterNTiles; cta_m_offset_ = 0; @@ -526,8 +490,7 @@ struct TileScheduler { total_valid_tiles_ = total_tiles_; cached_expert_ = 0; cached_expert_start_ = 0; - // Single expert: the cache fast path must always hit (the - // slow path dereferences masked_m, which is nullptr here). + // Force a cache hit: the slow path would read null masked_m. cached_expert_end_ = 0xFFFFFFFFu; } else { total_valid_tiles_ = 0; @@ -545,17 +508,14 @@ struct TileScheduler { cached_expert_end_ = 0; } - // Defaults for the non-compact path (stream-K is compact/Naive-only). k_begin_ = 0; k_end_ = k_tiles_; partial_slot_ = -1; current_tile_id_ = cluster_idx; advance_step_ = cluster_num_; - // Strided default; stream-K tail ids lie inside total_valid_tiles_. tile_end_ = total_valid_tiles_; if (chunked_assign_) { - // Range [cluster_idx*chunk, +chunk), clamped to the tile count. uint32_t chunk = (total_valid_tiles_ + cluster_num_ - 1) / cluster_num_; uint32_t base = cluster_idx * chunk; @@ -584,7 +544,6 @@ struct TileScheduler { // K-tile range of this work item; producer and consumer must agree. CUTLASS_DEVICE uint32_t k_begin() const { return k_begin_; } CUTLASS_DEVICE uint32_t k_end() const { return k_end_; } - // >= 0 when this item computed only a K-slice and deposits an fp32 partial. CUTLASS_DEVICE int partial_slot() const { return partial_slot_; } CUTLASS_DEVICE void advance() { @@ -656,8 +615,8 @@ struct TileScheduler { cluster_m = local_cluster_m; cluster_n = expert_first_cluster_tile(expert) + local_cluster_n; } else if (traverse_m_fast_) { - // M-fast: divisor was expert_ctm_, so r indexes M and q indexes N. - cluster_m = expert_first_cluster_tile(expert) + static_cast(r); + cluster_m = + expert_first_cluster_tile(expert) + static_cast(r); cluster_n = static_cast(q); } else { uint32_t local_cluster_m = q; @@ -730,10 +689,7 @@ struct TileScheduler { // Scan forward from current_tile_id_ to find the next valid tile, // caching its coordinates in m_idx_/n_idx_/expert_idx_/is_valid_. CUTLASS_DEVICE void find_next_valid_tile() { - // Quantized dense fast path: every tile is valid, so a plain divmod - // resolves it without the compact scan. Guarded to !KIsBF16 (BF16 - // needs the stream-K fold and M-fast path) and !traverse_m_fast_ - // (the divmod below assumes N-fast). + // This fast path excludes stream-K folding and M-fast traversal. if constexpr (KDenseW8A8MXFP8 && !UseTileSwizzle && !KernelTraits::KIsBF16) { if (!traverse_m_fast_) { @@ -757,15 +713,9 @@ struct TileScheduler { } } if (kAlwaysCompact || use_compact_sched_) { - // The tile space only holds valid cluster-tiles, so jump straight - // to the current one; a per-CTA check covers the last expert row - // whose CTAs run past masked_m. Chunked assignment ends at - // tile_end_. + // Valid cluster tiles may still contain rows beyond masked_m. while (current_tile_id_ < tile_end_) { uint32_t cluster_m, cluster_n, expert; - // Stream-K: ids past streamk_tail_base_ are (tail tile, - // K-chunk) pairs; resolve base tile, K range and slot once so - // all roles agree. uint32_t base_tile_id = current_tile_id_; k_begin_ = 0; k_end_ = k_tiles_; diff --git a/csrc/kernel/gemm/utils.cuh b/csrc/kernel/gemm/utils.cuh index 1e95175..75549de 100644 --- a/csrc/kernel/gemm/utils.cuh +++ b/csrc/kernel/gemm/utils.cuh @@ -73,11 +73,9 @@ struct GemmKernelConfig { static constexpr bool SkipTmemFence = false; static constexpr EpilogueOp KEpiOp = EpilogueOp::Identity; static constexpr bool KSwapSfbRun = false; - // Epilogue warp groups; 0 = auto (SwapAB ? 1 : 2). KEpiComputeN must be - // >= 32 when CtaM == 64, so narrow tiles (e.g. 64x32) need 1. + // 0 selects automatically; CtaM=64 requires KEpiComputeN >= 32. static constexpr int KEpilogueWarpGroupsOverride = 0; - // Force N predication even for power-of-two KBlockN (e.g. N=1600 on a - // 128-wide tile). + // Predicate N tails even for power-of-two tiles. static constexpr bool KForceEpiNPredicate = false; }; diff --git a/halops/gemm/batch_gemm.py b/halops/gemm/batch_gemm.py index 3c9a686..e8c3e04 100644 --- a/halops/gemm/batch_gemm.py +++ b/halops/gemm/batch_gemm.py @@ -66,9 +66,7 @@ def batch_gemm( sfb: [B, N, sf_k] scale factor for B, dtype uint8, same SfAtom layout as sfa. output: [M, B * N] pre-allocated output tensor, dtype bfloat16, or float8_e4m3fn (``w8a8-mxfp8``) for an MXFP8-quantized output. - ``mode="bf16"`` also accepts the contiguous batch-major - ``[B, M, N]`` layout, which writes faster when ``B`` is large and - ``N`` is narrow. + ``mode="bf16"`` also accepts contiguous ``[B, M, N]`` output. bias: Optional [B, N] bfloat16 bias vector. Only supported in w8a8-mxfp8 mode. alpha: Optional float32 per-batch scaling factor with shape [B], one value per batch item. Required for ``w4a4-nvfp4``; not accepted for diff --git a/tests/test_batch_gemm.py b/tests/test_batch_gemm.py index 2e567ca..3910f29 100644 --- a/tests/test_batch_gemm.py +++ b/tests/test_batch_gemm.py @@ -102,9 +102,7 @@ def ref_batch_gemm_fp4(x_fp4_float, w_fp4_float): def ref_batch_gemm_bf16(x, w): - """BF16 Batch GEMM reference: fp32 x[b] @ w[b]^T rounded to bf16, [B, M, N]. - x: [B, M, K] bfloat16, w: [B, N, K] bfloat16 - """ + """FP32 batch matmul rounded to BF16, with [B, M, N] output.""" return torch.matmul(x.to(torch.float32), w.to(torch.float32).transpose(1, 2)).to( torch.bfloat16 ) @@ -725,11 +723,6 @@ def test_batch_gemm_mxfp4_determinism(): assert torch.equal(out1, out2), "MXFP4 batch_gemm output is not deterministic" -# ===================================================================== -# BF16 correctness tests -# ===================================================================== - - def make_bf16_inputs(B, M, N, K): x = torch.randn([B, M, K], dtype=torch.bfloat16) w = torch.randn([B, N, K], dtype=torch.bfloat16) @@ -760,7 +753,6 @@ def test_batch_gemm_bf16(B, M, N, K): ], ) def test_batch_gemm_bf16_batch_major_output(B, M, N, K): - """mode="bf16" also accepts a contiguous [B, M, N] output.""" x, w, ref_out = make_bf16_inputs(B, M, N, K) output = torch.zeros([B, M, N], dtype=torch.bfloat16) batch_gemm(x, w, None, None, output, mode="bf16") diff --git a/tests/test_dense_gemm.py b/tests/test_dense_gemm.py index a9e9311..6622d53 100644 --- a/tests/test_dense_gemm.py +++ b/tests/test_dense_gemm.py @@ -76,7 +76,7 @@ def ref_gemm_w4a4(x_fp4_float, w_fp4_float): def ref_gemm_bf16(x, w): - """Reference BF16 GEMM: fp32 matmul of x (m, k) and w (n, k), rounded to bf16.""" + """FP32 matmul rounded to BF16.""" return torch.matmul(x.to(torch.float32), w.to(torch.float32).T).to(torch.bfloat16) @@ -435,22 +435,15 @@ def test_gemm_mxfp4_bad_scale_shape(): dense_gemm(x, w, sfa, sfb, out, None, None, -1, "w4a4-mxfp4") -# ===================================================================== -# BF16 tests -# ===================================================================== - - @pytest.mark.parametrize( "m, n, k", [ pytest.param(4096, 256, 256, id="large_m-4096x256x256"), - # 1600 % 128 == 64: the 256x128 predicated N-tail tile, at every M rung. pytest.param(1024, 1600, 4096, id="ntail-1024x1600x4096"), pytest.param(2048, 1600, 4096, id="ntail-2048x1600x4096"), pytest.param(4096, 1600, 4096, id="ntail-4096x1600x4096"), pytest.param(8192, 1600, 4096, id="ntail-8192x1600x4096"), pytest.param(16384, 1600, 4096, id="ntail-16384x1600x4096"), - # The 256-wide family underfills a wave, so large M steps down to 64xN. pytest.param(4096, 128, 4096, id="large_m_n128-4096x128x4096"), pytest.param(8192, 128, 4096, id="large_m_n128-8192x128x4096"), pytest.param(128, 256, 256, id="mid_m-128x256x256"), diff --git a/tests/test_group_contiguous_gemm.py b/tests/test_group_contiguous_gemm.py index 8066316..c28ebdf 100644 --- a/tests/test_group_contiguous_gemm.py +++ b/tests/test_group_contiguous_gemm.py @@ -135,10 +135,7 @@ def ref_group_contiguous_gemm_w4a4(x_fp4_float, w_fp4_float, expert_ids, num_exp def ref_group_contiguous_gemm_bf16(x, w, expert_ids, num_experts): - """ - Reference implementation of BF16 grouped contiguous GEMM. - x: (M, K) bfloat16, w: (num_experts, N, K) bfloat16, expert_ids: (M,) int32 - """ + """Per-expert FP32 matmul rounded to BF16, routed by expert_ids.""" ref_out = torch.zeros([x.shape[0], w.shape[1]], dtype=torch.bfloat16) for expert_id in range(num_experts): rows = expert_ids == expert_id @@ -501,11 +498,6 @@ def test_group_contiguous_w4a8_mxfp4(m, n, k, num_experts, tile_m): assert_close_per_expert(output, ref_out, inp.token_nums, W4A4_TOL) -# ===================================================================== -# BF16 accuracy tests -# ===================================================================== - - @pytest.mark.parametrize( "m, n, k, num_experts, tile_m", [pytest.param(512, 256, 128, 2, 128, id="mid_m_e2")], diff --git a/tests/test_group_masked_gemm.py b/tests/test_group_masked_gemm.py index d764970..de1fa8b 100644 --- a/tests/test_group_masked_gemm.py +++ b/tests/test_group_masked_gemm.py @@ -184,15 +184,7 @@ def ref_group_masked_gemm_w4a4( def ref_group_masked_gemm_bf16(x, w, masked_m, max_m_per_expert, num_experts): - """ - Reference implementation of BF16 grouped masked GEMM. - Each expert's valid rows get an fp32 matmul rounded to bf16; masked rows stay 0. - - Parameters: - x: (M_total, K), bfloat16 - w: (num_experts, N, K), bfloat16 - masked_m: (num_experts,), int - """ + """Per-expert FP32 matmul rounded to BF16; masked rows stay zero.""" ref_out = torch.zeros([x.shape[0], w.shape[1]], dtype=torch.bfloat16) for expert_id in range(num_experts): start = expert_id * max_m_per_expert @@ -697,11 +689,6 @@ def test_group_masked_w4a8_mxfp4(max_m_per_expert, num_experts, n, k, full_x, ma ) -# ===================================================================== -# BF16 accuracy tests -# ===================================================================== - - @pytest.mark.parametrize( "max_m_per_expert, num_experts, n, k, masked_m", [pytest.param(128, 2, 256, 128, [100, 128], id="mid_m_partial_mask")],