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..cb3fce8 --- /dev/null +++ b/benchmark/ci_configs/gemm/batch_bf16.yaml @@ -0,0 +1,20 @@ +scenario: batch_gemm +mode: bf16 + +# Shapes: [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..3f129fa --- /dev/null +++ b/benchmark/ci_configs/gemm/dense_bf16.yaml @@ -0,0 +1,20 @@ +scenario: dense_gemm +mode: bf16 + +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..38565a4 --- /dev/null +++ b/benchmark/configs/gemm/batch_bf16.yaml @@ -0,0 +1,21 @@ +# Shapes: [B, M, N, K]. +scenario: batch_gemm +mode: bf16 + +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, 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..3931f1b --- /dev/null +++ b/benchmark/configs/gemm/dense_bf16.yaml @@ -0,0 +1,19 @@ +scenario: dense_gemm +mode: bf16 +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, 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..e222900 --- /dev/null +++ b/benchmark/configs/gemm/group_contiguous_bf16.yaml @@ -0,0 +1,19 @@ +scenario: group_contiguous +mode: bf16 + +# Shapes: [num_experts, max_m, N, K]. +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..118de54 --- /dev/null +++ b/benchmark/configs/gemm/group_masked_bf16.yaml @@ -0,0 +1,19 @@ +scenario: group_masked +mode: bf16 + +# Shapes: [num_experts, max_m, N, K]. +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..b28ed5f 100644 --- a/benchmark/kernel/gemm/backends/deepgemm.py +++ b/benchmark/kernel/gemm/backends/deepgemm.py @@ -68,6 +68,14 @@ 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": + return { + "a": x_bf16, + "b": w_bf16, + "out": out, + "mode": mode, + } + cast = ( dg.per_token_cast_to_fp4 if mode.startswith("w4a4") @@ -112,6 +120,17 @@ 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": + 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 +213,16 @@ def make_grouped_contiguous_inputs( dev = x_bf16.device m_indices = m_indices.to(device=dev, dtype=torch.int32) + if mode == "bf16": + 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 +276,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 +300,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 +325,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..54fb2d1 100644 --- a/benchmark/kernel/gemm/backends/flashinfer.py +++ b/benchmark/kernel/gemm/backends/flashinfer.py @@ -47,6 +47,13 @@ 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": + 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 +82,19 @@ def run_fi_dense_gemm(inp: dict): ) +def run_fi_batch_gemm(inp: dict): + """Run FlashInfer batched BF16 GEMM.""" + _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 +103,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..cca7332 100644 --- a/benchmark/kernel/gemm/backends/golden.py +++ b/benchmark/kernel/gemm/backends/golden.py @@ -89,11 +89,16 @@ 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": + 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 +115,25 @@ 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": + x = inp["x_bf16"] + w_src = inp["w_bf16"] + w = w_src + else: + 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 + ) 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..be48e16 --- /dev/null +++ b/benchmark/kernel/gemm/scenarios/batch_gemm.py @@ -0,0 +1,319 @@ +""" +# 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 batch GEMM benchmark. Shapes: [B, M, N, K]. +Reports use num_experts=B and per-item m=M. +""" + +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 + 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) + + return BatchGemmInput( + x=x, + w=w, + out=out, + 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, + "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: + """Transpose weights [B, N, K] to a [B, K, N] view for FlashInfer.""" + 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"] + 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 + + # FLOPs use total B*M; bandwidth and reports use B and per-item M. + metrics = compute_gemm_metrics( + timing, + b * m, + n, + k, + dtype_bytes=dtype_bytes, + baseline_us=baseline_us, + gpu_type=cfg.get("gpu_type", "b200"), + num_experts=b, + ) + 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, + 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..3485569 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,27 @@ def _build_inputs( ) is_nvfp4 = mode == "w4a4-nvfp4" + if mode == "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 = 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 +149,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 +300,15 @@ 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" + 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..160419b 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,15 @@ def _make_grouped_tensors(num_experts: int, max_m: int, n: int, k: int, mode: st ) is_nvfp4 = mode == "w4a4-nvfp4" + if mode == "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 +262,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 +404,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 +515,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..2b41687 --- /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": 347.946 + }, + { + "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": 1859.059 + }, + { + "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": 900.468 + }, + { + "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": 197.99 + }, + { + "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": 105.0 + }, + { + "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": 183.725 + }, + { + "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.047 + }, + { + "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.184 + }, + { + "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.431 + } + ] +} diff --git a/ci/baselines/gemm/dense_bf16.json b/ci/baselines/gemm/dense_bf16.json new file mode 100644 index 0000000..29c19a8 --- /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 + } + ] +} diff --git a/csrc/common/cpp_extensions.cc b/csrc/common/cpp_extensions.cc index e3c2abe..61ebc4a 100644 --- a/csrc/common/cpp_extensions.cc +++ b/csrc/common/cpp_extensions.cc @@ -71,8 +71,9 @@ 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, - torch::Tensor& output, const std::optional& bias, + 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, const EpilogueOp epilogue, @@ -81,7 +82,8 @@ void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, 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 std::optional& sfa, + const std::optional& sfb, const torch::Tensor& masked_m, torch::Tensor& output, const std::optional& bias, const std::optional& alpha, @@ -89,16 +91,18 @@ void GroupMaskedGemm(const torch::Tensor& input, const torch::Tensor& weight, 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, - torch::Tensor& output, const std::optional& bias, + 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, const std::optional& output_sf, diff --git a/csrc/kernel/gemm/batch_gemm.cu b/csrc/kernel/gemm/batch_gemm.cu index 12f7549..e629ff5 100644 --- a/csrc/kernel/gemm/batch_gemm.cu +++ b/csrc/kernel/gemm/batch_gemm.cu @@ -21,22 +21,24 @@ namespace halops { void BatchGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, - torch::Tensor& output, const std::optional& bias, + 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, const std::optional& output_sf, 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, "weight must be a 3D tensor of shape [B, N, K]"); - TORCH_CHECK(output.dim() == 2, + 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); @@ -45,8 +47,23 @@ 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]"); + // 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(), + "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); @@ -65,8 +82,40 @@ 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 == "w8a8-mxfp8") { + if (mode == "bf16") { + 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; + 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 " + "(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), @@ -74,8 +123,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(); } @@ -131,6 +180,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 ", @@ -138,19 +190,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 46124ab..0e7e054 100644 --- a/csrc/kernel/gemm/dense_gemm.cu +++ b/csrc/kernel/gemm/dense_gemm.cu @@ -21,8 +21,9 @@ namespace halops { void DenseGemm(const torch::Tensor& input, const torch::Tensor& weight, - const torch::Tensor& sfa, const torch::Tensor& sfb, - torch::Tensor& output, const std::optional& bias, + 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, const bool use_pdl, const EpilogueOp epilogue, @@ -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,49 @@ 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") { + 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; + + 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::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"); + } + 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 " + "(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), @@ -78,21 +122,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 ", @@ -124,6 +168,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), @@ -132,8 +179,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"; @@ -143,16 +190,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/epilogue.cuh b/csrc/kernel/gemm/epilogue.cuh index 125d837..f28e0ec 100644 --- a/csrc/kernel/gemm/epilogue.cuh +++ b/csrc/kernel/gemm/epilogue.cuh @@ -52,6 +52,8 @@ class CollectiveEpilogue { using CopyOpT2R = typename KernelTraits::CopyOpT2R; using CopyOpT2R_Sub = typename KernelTraits::CopyOpT2R_Sub; using OverlapComputeTile = typename KernelTraits::OverlapComputeTile; + 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 = @@ -92,6 +94,10 @@ class CollectiveEpilogue { int rows_per_batch = 0; SituCoef situ{}; int64_t gate_ld = 0; + bool batch_out_bmn = false; + // Stream-K fp32 partial workspace: [slot][CtaShape_M][KBlockN]; null + // when stream-K is off. + TypeAccumulate* ptr_partial = nullptr; }; struct Params { @@ -108,6 +114,8 @@ class CollectiveEpilogue { TypeC const* ptr_c = nullptr; int64_t d_ld; int64_t gate_ld; + bool batch_out_bmn = false; + TypeAccumulate* ptr_partial = nullptr; }; static Params to_underlying_arguments(Arguments const& args) { @@ -129,7 +137,8 @@ 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; + 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>( @@ -154,7 +163,9 @@ class CollectiveEpilogue { args.situ, args.ptr_c, d_ld, - args.gate_ld}; + args.gate_ld, + args.batch_out_bmn, + args.ptr_partial}; } // Producer warp: TMA-loads one bias C stage per scheduled tile. @@ -260,6 +271,32 @@ class CollectiveEpilogue { return 0; } } + // 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) { + if constexpr (KernelTraits::KernelType == KernelMode::Batch) { + 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; + } else { + return shift; + } + } else { + return 0; + } + } + 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; @@ -447,10 +484,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 + @@ -710,7 +744,7 @@ class CollectiveEpilogue { } } - template + template CUTLASS_DEVICE void epilogue(Params const& epilogue_params, AccumulatorPipeline& acc_pipeline, BiasPipeline& bias_pipeline, @@ -757,6 +791,16 @@ 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); + // BF16 uses partitioned T2R for 16dp and 2SM 2x2 layouts. + constexpr bool kPartitionedLoad = KernelTraits::KIsBF16; + // 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); + 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( @@ -790,6 +834,46 @@ 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; + } + }; + + // 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 = [&]() { + 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 + @@ -802,6 +886,71 @@ class CollectiveEpilogue { } int buf_i = 0; + 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()) { @@ -810,12 +959,19 @@ 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 = 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; @@ -862,7 +1018,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) { @@ -905,13 +1069,29 @@ class CollectiveEpilogue { } } else { const int sub_idx = wg * kUnits + u; - if constexpr (KernelTraits::IsSfbUnaligned && !SwapAB) { + // N alignment makes each sub-tile wholly in or out. + if constexpr ((KernelTraits::IsSfbUnaligned && + !SwapAB) || + KernelTraits::KEpiNeedsNPredicate) { if (n_idx * cute::size<1>(TileShape{}) + sub_idx * kSubN >= out_n) { return; } } + // 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)); + return; + } + } if constexpr (AddBias) { cute::copy( tiled_s2r_bias, @@ -922,7 +1102,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]); } @@ -947,7 +1131,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 = @@ -988,66 +1172,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(); } diff --git a/csrc/kernel/gemm/gemm_dispatch.cuh b/csrc/kernel/gemm/gemm_dispatch.cuh index f3b4cb9..e6d06b8 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,13 +357,34 @@ inline int PickTile(const TileSpec* tiles, int count, MmaKind kind, // Dispatch using TileLauncher = void (*)(GemmParams&, const GemmShape&, cudaStream_t); -template +// 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 = + 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, 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()))) { + if constexpr (Kind == MmaKind::BF16) { + CheckBF16TileShape("BF16 GEMM", S, shape.m, shape.n, shape.k); + } using T = MmaTraits; using TypeD = cute::conditional_t; @@ -376,28 +398,37 @@ 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; return on; } +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; 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, @@ -417,4 +448,494 @@ void LaunchCfg(GemmParams& params, GemmShape shape, cudaStream_t stream) { kTileLaunchers[pick](params, shape, stream); } +// BF16 dispatch uses empirically tuned shape and wave-fill thresholds. +namespace bf16 { + +// K quantum used by the ladder's depth gates. +inline constexpr int kBlockK = 64; + +// 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; + +// Tuned K-tile cap for 256x128 A rereads. +inline constexpr int kNarrowPairMaxKTiles = 64; + +// Tuned A-reread cap: k_tiles * n_tiles for 64-row tiles. +inline constexpr int kRereadsCap = 2048; + +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); +} + +// 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; + } + 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); + 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; +} + +// 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) && + (coarse_ctas <= 4 * target) && + FillsLastWaveBetter(coarse_ctas, fine_ctas, target); +} + +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; +} + +// 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; + } + 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; +} + +enum DenseTile : int { + 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 >= 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) { + 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); + 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; + } + if (n % 64 == 0) { + return kPair256x128Ntail; + } + return kPair256x64; +} + +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)); +} + +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; + }; + // 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); + // 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; + } + if (pair_tn == 256 && (n % 128 == 0) && + (step_ok(256, 128) || + UseNarrowPairTile(n, k, pair_ctas(256), pair_ctas(128), target))) { + pair_tn = 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; + // 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; + // 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 = + 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: + // Tuned: prefer 1-CTA 128x64 for <=32 K-tiles. + 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; + } + + 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) { + // 64x32 requires one epilogue warp group. + if (2 * tiles64 <= target && n % 32 == 0) { + return UseDeepPipeline(k) ? kM64x32_1wgP18 : kM64x32_1wg; + } + return UseDeepPipeline(k) ? kM64x64_1wgP14 : kM64x64_1wg; + } + } + + if (m % 256 == 0) { + const int pair = SelectPair256xNTile(m, n, k, target); + if (pair >= 0) { + return pair; + } + } + + const int pick_tn = Pick128xNWidth(m, n, target); + auto tiles = [&](int tm, int tn) { + return CeilDiv(m, tm) * CeilDiv(n, tn); + }; + + const int ctas96 = CeilDiv(m, 64) * CeilDiv(n, 96); + const int ctas224 = CeilDiv(m, 64) * CeilDiv(n, 224); + // 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) + : tiles(128, pick_tn); + auto fills_better = [&](int64_t c) { + return c <= target && 2 * c > target && + (incumbent_ctas > target || c > incumbent_ctas); + }; + // 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); + 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; + } + + if ((m % 64 == 0) && (n % 128 == 0) && tiles(128, pick_tn) > target && + tiles(64, 128) <= target) { + return kM64x128; + } + + 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) { + // 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; + } + return kPair128x64P18; + } + } + + return pick_tn == 256 + ? kM128x256 + : (pick_tn == 128 ? kM128x128 + : (pick_tn == 64 ? kM128x64 : kM128x32)); +} + +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; +} + +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; + } + 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 = sm_count > 0 ? sm_count : GetSmCount(); + 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); +} + +enum ContiguousTile : int { + 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 >= 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) { + if (m >= 4096) { + return kContPair256x256; + } + if (m >= 128) { + // 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); + }; + // 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) { + // Tuned 256x128 cluster-count cap: 2 * target. + const bool square_like = (n % 128 == 0) && (clusters <= 2 * target); + return square_like ? kContPair256x128 : kContPair256x256; + } + // 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; + } + return kContM128x128; + } + return kContM128x256; + } + return kContSwap128x64; +} + +enum MaskedTile : int { + 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 >= 0 && + kMaskPair256x128 < static_cast(kBF16Tiles.size()), + "BF16 masked tile id outside kBF16Tiles"); + +// mm is padded rows per expert. +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 = sm_count > 0 ? sm_count : GetSmCount(); + 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 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; + } + return kMaskM128x128; + } + return kMaskM128x256; + } + return kMaskSwap128x64; +} + +enum BatchTile : int { + kBatchPair256x256 = Bf16TileId(kBF16_256x256_pair), + kBatchM128x256 = Bf16TileId(kBF16_128x256_ovlp16), + kBatchSwap128x64 = Bf16TileId(kBF16_128x64_swap), +}; +static_assert(kBatchSwap128x64 >= 0 && + kBatchSwap128x64 < static_cast(kBF16Tiles.size()), + "BF16 batch tile id outside kBF16Tiles"); + +// 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; + } + if (m % 128 == 0 && n % 256 == 0) { + return kBatchM128x256; + } + if (m % 64 == 0 && n % 128 == 0) { + return kBatchSwap128x64; + } + return -1; +} + +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 } // namespace halops diff --git a/csrc/kernel/gemm/gemm_kernel.cuh b/csrc/kernel/gemm/gemm_kernel.cuh index a30584a..b98f54f 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, @@ -88,16 +90,19 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) 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 +197,10 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) BiasPipeline bias_pipeline(shared_storage.bias_pipeline, bias_pipeline_params); + // The CTA/cluster sync below publishes tmem_base_ptr. TmemAllocator tmem_allocator{}; if (warp_idx == KernelTraits::KMmaWarpId) { - tmem_allocator.allocate(TmemAllocator::Sm100TmemCapacityColumns, + tmem_allocator.allocate(KernelTraits::KTmemColumns, &shared_storage.tmem_base_ptr); } @@ -219,11 +225,13 @@ __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 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) { - // Non-epilogue warps hand registers to the epilogue warps. - if constexpr (KEpilogueWarpGroupCount != 1) { + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } main_loop.tma_loadAB(mainloop_params, mainloop_pipeline, shared_storage, @@ -232,39 +240,42 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) pdl_trigger(); } } else if (warp_idx == KernelTraits::KMmaWarpId && is_mma_leader_cta) { - if constexpr (KEpilogueWarpGroupCount != 1) { + // MMA accumulators live in TMEM. + 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(); } + // 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) { - if constexpr (KEpilogueWarpGroupCount != 1) { + 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) { + if constexpr (KernelTraits::KRedistributeRegs) { cutlass::arch::warpgroup_reg_dealloc(); } } @@ -280,7 +291,7 @@ __global__ void __launch_bounds__(KernelTraits::KThreads, 1) if (warp_idx == KernelTraits::KMmaWarpId) { tmem_allocator.release_allocation_lock(); tmem_allocator.free(shared_storage.tmem_base_ptr, - TmemAllocator::Sm100TmemCapacityColumns); + KernelTraits::KTmemColumns); } } @@ -303,10 +314,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 +436,19 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, "gemm_impl requires M to be divisible by KBlockM=", KernelTraits::KBlockM, ", got ", params.m); if constexpr (KernelTraits::IsSfbUnaligned) { + // 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) { + // Predicated N tails require KSubTileN alignment. + 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=", @@ -447,13 +469,11 @@ void CheckGemmKernelLaunchParams(const GemmParams& params, 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 +483,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"); } @@ -486,7 +505,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{}); const int raw_sm_count = sm_count > 0 ? sm_count : GetSmCount(); - // Only launch full clusters. + // Launch only full clusters. const int runtime_sm_count = (raw_sm_count / KCTAsPerCluster) * KCTAsPerCluster; int M = params.m; @@ -522,7 +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>{})); - // meet the cutlass's 128 row SfAtoms layout. + // 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( @@ -548,6 +567,29 @@ 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; + 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); + + 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 +600,10 @@ 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, params.batch_out_bmn, + streamk_active ? streamk_ws.data_ptr() : nullptr}); + // 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"); @@ -575,6 +613,17 @@ void gemm_impl_body(GemmParams& params, const int sm_count, int smem_size = cutlass::arch::sm100_smem_capacity_bytes; + 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 +632,27 @@ 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) { + 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 #include +#include #include #include "common/mx_quant.cuh" @@ -26,12 +27,15 @@ namespace halops { inline constexpr int kSwapEpiChunk = 2 * kMatRows; inline constexpr int kSfbRowShiftAlign = 64; +// SwapAB: BM tiles weights, BN activations. +// SFVS: 16 = NVFP4, 32 = MXFP4. 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 +54,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; + // 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; + static constexpr bool KForceEpiNPredicate = NTAIL; + static constexpr bool KIsBF16 = BF16; static constexpr EpilogueOp KEpiOp = OP; static constexpr bool KSwapSfbRun = SWAP; }; @@ -75,6 +84,8 @@ struct TileSpec { 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; // 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. @@ -158,6 +169,20 @@ 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; + // Unused placeholder: BF16 has no scale factors. + 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 = @@ -165,7 +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>; + Mode, Op, S.epi_warp_groups, S.force_ntail, Kind == MmaKind::BF16>; // Fp8 constexpr TileSpec kFp8_128x256 = {.block_m = 128, @@ -429,4 +454,243 @@ struct CandidateTiles { static constexpr const auto& tiles = kW4a8Tiles; }; +// 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, + .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}; + +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}; + +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, kBF16_128x256_ovlp16, + kBF16_128x128_p6, kBF16_128x64_ovlp16, +}; + +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"; +} + +template <> +struct CandidateTiles { + static constexpr const auto& tiles = kBF16Tiles; +}; +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( + 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( + 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/gemm_utils.h b/csrc/kernel/gemm/gemm_utils.h index 98da2c4..30d1c58 100644 --- a/csrc/kernel/gemm/gemm_utils.h +++ b/csrc/kernel/gemm/gemm_utils.h @@ -59,4 +59,9 @@ 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); +} + } // namespace halops diff --git a/csrc/kernel/gemm/group_contiguous_gemm.cu b/csrc/kernel/gemm/group_contiguous_gemm.cu index a442bfc..d64110c 100644 --- a/csrc/kernel/gemm/group_contiguous_gemm.cu +++ b/csrc/kernel/gemm/group_contiguous_gemm.cu @@ -21,8 +21,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, @@ -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,16 +65,45 @@ void GroupContiguousGemm(const torch::Tensor& input, params.num_experts = num_experts; params.use_pdl = true; - if (mode == "w8a8-mxfp8") { + if (mode == "bf16") { 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 = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + 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); + } 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), + ", weight K=", k); + 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(); if (bias.has_value()) { params.ptr_c = bias->data_ptr(); } @@ -87,6 +118,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, " @@ -95,16 +129,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, @@ -116,6 +150,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), @@ -124,18 +161,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 e672725..7dfdb76 100644 --- a/csrc/kernel/gemm/group_masked_gemm.cu +++ b/csrc/kernel/gemm/group_masked_gemm.cu @@ -21,7 +21,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, @@ -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,16 +74,44 @@ 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") { 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 = sfa.data_ptr(); - params.ptr_sfb = sfb.data_ptr(); + 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); + } 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), + ", weight K=", k); + 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(); if (bias.has_value()) { params.ptr_c = bias->data_ptr(); } @@ -95,6 +125,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, " @@ -103,16 +136,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, @@ -123,6 +156,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), @@ -131,18 +167,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/csrc/kernel/gemm/kernel_traits.cuh b/csrc/kernel/gemm/kernel_traits.cuh index 1444d51..d28fd76 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; @@ -88,16 +90,23 @@ struct GemmKernelTraits { 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. + // 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; the epilogue drops D past M). static constexpr bool KNarrowA = NarrowA_ && (KDenseW8A8MXFP8 || (KernelType == KernelMode::Batch && !AddBias)) && - !SwapAB && !IsPairUmma && !KernelConfig_::KIsFP4 && KBlockK == 128; + !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); + // 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) && + !KernelConfig_::KForceEpiNPredicate; static constexpr int kItersK = KBlockK / KMmaK; static constexpr bool KBFp4Unpack = !KIsFP4 && cute::sizeof_bits_v == 4; @@ -123,10 +132,12 @@ struct GemmKernelTraits { // Epilogue warp groups split N: 1 for bf16 SwapAB (small N) and for a // quantized tile narrower than two quant groups, 2 otherwise. 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 +148,11 @@ struct GemmKernelTraits { static constexpr int KNumRegsEpilogue = KernelConfig_::KNumRegsEpilogue; static constexpr bool SkipTmemFence = KernelConfig_::SkipTmemFence; static constexpr int KNumRegsOther = 88; + // Redistribute BF16 registers to avoid a flat per-warp epilogue budget. + static constexpr bool KRedistributeRegs = + KIsBF16 + ? (KNumWarp >= 8 && (!SwapAB || KernelType == KernelMode::Dense)) + : KEpilogueWarpGroupCount != 1; using TileShape = cute::Shape, cute::Int, cute::Int>; @@ -148,20 +164,32 @@ 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. + // 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); 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); + 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>>; - 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 = @@ -169,49 +197,150 @@ 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). + // 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; + while (r < v) { + r *= 2; + } + return r > 512 ? 512 : r; + } + static constexpr int KTmemColumns = + (KIsBF16 && KTmemOverlapCols == 0) + ? round_up_tmem_columns(KAccTmemColumns) + : 512; + + 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)."); + 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."); + + // 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; + 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."); + 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< + KIs2SmHalfM, + cute::conditional_t< + KEpiComputeN == 128, cute::SM100_TMEM_LOAD_32dp32b64x, + cute::conditional_t>, + cute::conditional_t< + 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>>>>>>; + // 16dp and 2x2 use N/2 TMEM columns per sub-tile. + static constexpr int KSubTileTmemCols = + (KEpiTmemDp == 16 || KIs2SmHalfM) ? KSubTileN / 2 : KSubTileN; + using CopyOpT2R_SubWide = cute::conditional_t< + KEpiTmemDp == 16, cute::conditional_t< - KEpiComputeN == 64, cute::SM100_TMEM_LOAD_32dp32b64x, + KSubTileTmemCols == 64, cute::SM100_TMEM_LOAD_16dp32b64x, 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 = + 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>>; + + 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."); + + // N predication is per KSubTileN; N must be a multiple of it. + 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; using MMA_T = cute::conditional_t< - KIsFP4, + KIsBF16, 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>>, - 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 +348,33 @@ 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. + // 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, + 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; + + // Unaligned-N SFB uses 128-row atoms, independent of the GEMM tile width. 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>; + 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{})); + 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; + // Unaligned SFB uses a whole-atom load window and an offset MMA address. + // One TMEM column covers 32 SF rows. 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 +432,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 +477,16 @@ 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{})); + 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 +538,10 @@ struct GemmKernelTraits { 128) cute::ArrayEngine> A; alignas( 128) cute::ArrayEngine> B; - alignas( - 128) cute::ArrayEngine> SFA; - alignas( - 128) cute::ArrayEngine> SFB; + 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; @@ -419,9 +582,8 @@ 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. + // 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; @@ -431,8 +593,9 @@ struct GemmKernelTraits { sf_full[KSfFullStages]; }; - static constexpr bool KActRowTma = - KernelType == KernelMode::Batch && SwapAB && IsPairUmma && !KIsFP4; + 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; @@ -459,7 +622,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..c445ddf 100644 --- a/csrc/kernel/gemm/mainloop_fwd.cuh +++ b/csrc/kernel/gemm/mainloop_fwd.cuh @@ -27,6 +27,8 @@ struct CollectiveMainloop { using TiledMma = typename KernelTraits::TiledMma; using TiledMma_SF = typename KernelTraits::TiledMma_SF; + using TiledMmaForSF = typename KernelTraits::TiledMmaForSF; + 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 +194,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 +259,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 +318,102 @@ 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, so return default-constructed 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"); - } - 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}; } - - 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 +433,7 @@ struct CollectiveMainloop { TileScheduler& scheduler) { bool select_thr = cute::elect_one_sync(); - uint32_t tile_num_k = + [[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 +486,9 @@ 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); + // 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{})); cute::Tensor gA = cute::local_tile( A, TileShape{}, cute::make_coord(cute::_, cute::_, cute::_), @@ -555,10 +582,14 @@ struct CollectiveMainloop { block_rank_in_cluster % cute::size(typename TiledMma_SF::AtomThrID{})); + // 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{})); 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,7 +699,10 @@ 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) { + // 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) { ab_pipeline.producer_acquire(mainloop_pipe_producer_state); BarrierType* tma_barrier = ab_pipeline.producer_get_barrier( mainloop_pipe_producer_state); @@ -718,12 +752,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) { + } else if constexpr (!IsSfbUnaligned) { cute::copy( mainloop_params.tma_load_SFB.with(*tma_barrier, mcast_mask_sfb), @@ -820,7 +858,7 @@ struct CollectiveMainloop { } } - template + template CUTLASS_DEVICE void mma(Params const& mainloop_params, MainloopPipeline& mainloop_pipeline, AccumulatorPipeline& accumulator_pipeline, @@ -829,13 +867,15 @@ struct CollectiveMainloop { TileScheduler& scheduler) { bool select_thr = cute::elect_one_sync(); - uint32_t tile_num_k = + [[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(); + 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 +925,18 @@ 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; + // Stream-K disables next-tile prefetch because K ranges vary. + [[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 +968,57 @@ 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) { + + 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) { + 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::_)); + 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) { + 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 +1033,15 @@ 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) { + 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..b514039 --- /dev/null +++ b/csrc/kernel/gemm/stream_k_reduce.cuh @@ -0,0 +1,93 @@ +// 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 + +// FP32 partials: [tail tile][split][CTA][CtaM][BlockN]. +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 [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; + 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); + + 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 (scheduler's linear path). + 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..d5bb654 100644 --- a/csrc/kernel/gemm/tile_scheduler.cuh +++ b/csrc/kernel/gemm/tile_scheduler.cuh @@ -57,6 +57,11 @@ struct TileScheduler { static constexpr int kExpertClusterRows = kExpertTileSize * kExpertClusterTiles; + // Without swizzle, S=1 and only the compact path is reachable. + static constexpr bool kAlwaysCompact = !UseTileSwizzle; + static constexpr bool kIsSingleCtaCluster = + (KernelTraits::KNumCTA == 1) && (cute::size(ClusterShape_MNK{}) == 1); + struct Params { int m; int n; @@ -70,10 +75,9 @@ struct TileScheduler { 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_blocks; // ÷ blocks_fast cutlass::FastDivmod divmod_s; // ÷ S - // Other compact state is derived on device (no D2H sync). bool use_compact_sched; int batch_own_tiles; cutlass::FastDivmod divmod_batch_period; @@ -81,12 +85,27 @@ struct TileScheduler { cutlass::FastDivmod divmod_own_tiles; int batch_valid_tiles; float batch_per_tile; + + // 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; + + // 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; + int k_tiles; // ceil_div(k, KBlockK) }; 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 +161,82 @@ 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; + // 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) { + 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); + int streamk_tail_base = total_tiles; + int streamk_rem = 0; + int streamk_splits = 1; + if constexpr (KernelTraits::KSupportsStreamK) { + // 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; + // 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'; + }(); + 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; + // Tuned break-even: >=5% idle SM-time. + const bool worth_it = + rem > 0 && (C - rem) * 20 >= (whole + 1) * C; + if (worth_it) { + // 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"); + 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)) { + // Tuned underfill minimum: 4 splits. + + streamk_tail_base = whole * C; + streamk_rem = rem; + streamk_splits = p; + total_tiles = streamk_tail_base + rem * p; + } + } + } + } + bool use_compact_sched = false; if (S == 1) { use_compact_sched = true; @@ -179,6 +268,18 @@ struct TileScheduler { kExpertClusterRows) : 0.f; + // 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) { + 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 +300,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 +319,8 @@ struct TileScheduler { uint32_t cluster_num_; // stride = number of clusters uint32_t current_tile_id_; // current position in global tile space + uint32_t advance_step_; + uint32_t tile_end_; uint32_t expert_ctm_; uint32_t expert_ctn_; @@ -234,6 +343,16 @@ struct TileScheduler { uint32_t batch_valid_tiles_; float batch_per_tile_; uint32_t act_row0_; + bool traverse_m_fast_; + bool chunked_assign_; + + uint32_t streamk_tail_base_; + uint32_t streamk_rem_; + uint32_t streamk_splits_; + uint32_t k_tiles_; + uint32_t k_begin_; + uint32_t k_end_; + 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. @@ -315,29 +434,49 @@ 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) { + 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_num_ = gridDim.x * gridDim.y; + cluster_idx = blockIdx.x * gridDim.y + blockIdx.y; + 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); + } + + if (kAlwaysCompact || use_compact_sched_) { if constexpr (IsBatch) { total_valid_tiles_ = batch_valid_tiles_; cached_expert_ = 0; @@ -351,7 +490,8 @@ struct TileScheduler { total_valid_tiles_ = total_tiles_; cached_expert_ = 0; cached_expert_start_ = 0; - cached_expert_end_ = total_tiles_; + // Force a cache hit: the slow path would read null masked_m. + cached_expert_end_ = 0xFFFFFFFFu; } else { total_valid_tiles_ = 0; for (uint32_t e = 0; e < num_experts_; e++) { @@ -368,7 +508,27 @@ struct TileScheduler { cached_expert_end_ = 0; } + k_begin_ = 0; + k_end_ = k_tiles_; + partial_slot_ = -1; + current_tile_id_ = cluster_idx; + advance_step_ = cluster_num_; + tile_end_ = total_valid_tiles_; + if (chunked_assign_) { + 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 +541,13 @@ struct TileScheduler { CUTLASS_DEVICE uint32_t max_m_per_expert() const { return max_m_per_expert_; } + // 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_; } + 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 +614,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_) { + 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 +689,52 @@ 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_; + // This fast path excludes stream-K folding and M-fast traversal. + 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_) { + // Valid cluster tiles may still contain rows beyond masked_m. + 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, + 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..75549de 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,6 +73,10 @@ struct GemmKernelConfig { static constexpr bool SkipTmemFence = false; static constexpr EpilogueOp KEpiOp = EpilogueOp::Identity; static constexpr bool KSwapSfbRun = false; + // 0 selects automatically; CtaM=64 requires KEpiComputeN >= 32. + static constexpr int KEpilogueWarpGroupsOverride = 0; + // Predicate N tails even for power-of-two tiles. + static constexpr bool KForceEpiNPredicate = false; }; static constexpr int get_num_warps(int load_c_warp_id, bool add_bias) { diff --git a/halops/gemm/batch_gemm.py b/halops/gemm/batch_gemm.py index baedb6d..e8c3e04 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, @@ -66,12 +66,15 @@ 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 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 ``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``, diff --git a/halops/gemm/dense_gemm.py b/halops/gemm/dense_gemm.py index ce367d0..7b82081 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`` diff --git a/halops/gemm/group_contiguous_gemm.py b/halops/gemm/group_contiguous_gemm.py index 390333a..6c8d515 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. diff --git a/halops/gemm/group_masked_gemm.py b/halops/gemm/group_masked_gemm.py index 7e485d0..66d82cb 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. diff --git a/tests/test_batch_gemm.py b/tests/test_batch_gemm.py index cd3e468..3910f29 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,13 @@ def ref_batch_gemm_fp4(x_fp4_float, w_fp4_float): return output +def ref_batch_gemm_bf16(x, w): + """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 + ) + + # ===================================================================== # Input builders # ===================================================================== @@ -715,5 +723,46 @@ def test_batch_gemm_mxfp4_determinism(): assert torch.equal(out1, out2), "MXFP4 batch_gemm output is not deterministic" +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): + 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..6622d53 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): + """FP32 matmul 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,62 @@ def test_gemm_mxfp4_bad_scale_shape(): dense_gemm(x, w, sfa, sfb, out, None, None, -1, "w4a4-mxfp4") +@pytest.mark.parametrize( + "m, n, k", + [ + pytest.param(4096, 256, 256, id="large_m-4096x256x256"), + 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"), + 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 +530,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 +607,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_group_contiguous_gemm.py b/tests/test_group_contiguous_gemm.py index c1ea69a..c28ebdf 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,17 @@ 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): + """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 + 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 +498,21 @@ 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) +@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..de1fa8b 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,18 @@ 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): + """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 + 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 +689,21 @@ def test_group_masked_w4a8_mxfp4(max_m_per_expert, num_experts, n, k, full_x, ma ) +@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