From 59f79ac702732348acbf74757a1b39eb586f8c44 Mon Sep 17 00:00:00 2001 From: Prasun Gera Date: Wed, 21 Oct 2026 21:11:11 -0700 Subject: [PATCH] feat(msa-v1): Q8KV4 prefill on SM107, faster K1 pipeline, TMA-ring combine with locality-domain placement Bring the Q8KV4 paged sparse prefill work from vllm-project/MSA dev (PRs 30 and 38) to nv_dev, adapted to this tree's layout and public contract. Build and dequant - Build the prefill extension for sm_107a (CUDA 13.5 or newer) next to sm_100a/sm_103a; select the dequant path with the shared QMUL4 toolchain probe, now in inference/msa_v1/_build_utils.py and used by the decode attention and decode indexer JITs instead of their private copies. - Dequantize with exact packed-FP16 math where QMUL4 is unavailable (SM107): an E2M1 x E4M3 product has at most five significant bits, so the only rounding is the final E4M3 conversion, as with QMUL4. K1 (attention forward) - Compute each partial-output row's pointer, scale and validity once per group and stream the row's chunks out one 64-column TMEM half at a time. - Prefetch the packed query indices eight groups at a time into a 32-slot metadata ring and deepen the Q ring to eight stages; every loader warp waits for its stage itself. - Skip the causal select for groups whose 128 keys are all visible, and hand the output and stats stages back as soon as the epilogue holds them in registers, before its stores drain. - Use the K=64 kind::f8f6f4 MMA on SM107 for QK and PV (the TS form is a local atom; CUTLASS 4.8 provides only the SS form). - Take the partial-output split stride from the tensor and zero the combine's tile counters for the launch that follows. Combine (K2) - Replace the cp.async combine with one TMA-ring kernel over the flattened varlen rows: 64-row tiles through a four-slot bulk-tensor ring (two slots for interleaved reads on SM107), the STG.128 column permutation undone by XOR shuffles, the LSE tile by one 2-D bulk copy or 4-byte cp.async when the head count is not a multiple of 4. BF16/FP16 partials only; the temperature-LSE and output-scale paths had no caller here. The BF16 and Q8KV8 prefill wrappers use the same kernel. combine.py becomes an inference-local implementation in vendor_manifest.json. Locality-domain placement - Add PrefillWorkspace: the wrapper owns its split partials, striped over the device's memory locality domains by 2 MB page through the CUDA virtual memory API, every split slab padded to the stripe; each combine CTA claims a tile from the domain of its own SM and steals from the other domains once its own are drained. One domain, an older driver or a refused localized allocation fall back to interleaved memory with the same kernels. MM_SPARSE_PREFILL_Q8KV4_LOCALITY_DOMAINS=0 keeps the buffer interleaved. Tests and docs - Direct combine tests (split counts, head counts, dtypes, padded slabs, unaligned LSE slabs, synthetic two-domain claiming), workspace contract tests (growth and reuse, knob, fallback, release with its owner), SM107 test and benchmark gates; READMEs in both languages. Co-Authored-By: Claude Fable 5.1 --- README.md | 12 +- README.zh-CN.md | 10 +- .../attention/prefill/q8kv4/benchmark.py | 4 +- inference/msa_v1/README.md | 2 +- inference/msa_v1/README.zh-CN.md | 2 +- inference/msa_v1/_build_utils.py | 97 + .../msa_v1/attention/decode/q8kv4/jit.py | 78 +- .../attention/prefill/_common/combine.py | 2823 +++++------------ .../prefill/_common/paged_interface.py | 2 - .../prefill/_common/vendor_manifest.json | 34 +- .../msa_v1/attention/prefill/q8kv4/README.md | 30 +- .../attention/prefill/q8kv4/README.zh-CN.md | 27 +- .../attention/prefill/q8kv4/__init__.py | 3 +- .../q8kv4/csrc/api/locality_domains.cu | 305 ++ .../q8kv4/csrc/api/prefill_attention_api.cpp | 34 +- .../q8kv4/csrc/api/prefill_attention_api.hpp | 39 +- .../csrc/api/prefill_attention_binding.cpp | 20 +- .../sm100_prefill_attention_fp4_transform.cuh | 21 +- .../sm100_prefill_attention_mainloop.cuh | 66 +- .../include/sm100/common/nvfp4_to_e4m3.cuh | 85 +- .../sm100/common/prefill_attention_config.cuh | 13 +- .../sm100/common/prefill_attention_math.cuh | 260 +- .../include/sm100/common/sm107_mma_ts.cuh | 112 + .../sm100/device/prefill_attention.hpp | 7 + .../sm100/device/prefill_attention_launch.cuh | 25 +- .../kernel/sm100_prefill_attention_kernel.cuh | 37 +- .../attention/prefill/q8kv4/interface.py | 217 +- .../msa_v1/attention/prefill/q8kv4/jit.py | 66 +- inference/msa_v1/indexer/decode/q8kv4/jit.py | 59 +- .../prefill/q8kv4/test_api_contract.py | 112 +- .../prefill/q8kv4/test_real_cases.py | 8 +- .../prefill/q8kv4/test_real_cuda_graph.py | 14 +- .../msa_v1/attention/prefill/test_combine.py | 209 ++ .../attention/test_probability_contract.py | 1 + 34 files changed, 2262 insertions(+), 2572 deletions(-) create mode 100644 inference/msa_v1/attention/prefill/q8kv4/csrc/api/locality_domains.cu create mode 100644 inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/sm107_mma_ts.cuh create mode 100644 tests/inference/msa_v1/attention/prefill/test_combine.py diff --git a/README.md b/README.md index c3112dbe..656738b9 100644 --- a/README.md +++ b/README.md @@ -119,15 +119,15 @@ python -c 'import cutlass; print(cutlass.__version__, cutlass.CUDA_VERSION)' ``` Q8KV4 C++ operators use the standard `CUDA_HOME`, `CUTLASS_ROOT`, and -`TORCH_EXTENSIONS_DIR` configuration. Runtime JIT always selects `sm_100a` or -`sm_103a` from the CUDA device of the input tensor. Tensor-less AOT/offline -builds use `MM_SPARSE_TARGET_ARCH=100a|103a` to select a target (default: -`103a`). `TORCH_CUDA_ARCH_LIST` is internal compiler plumbing rather than the +`TORCH_EXTENSIONS_DIR` configuration. Runtime JIT always selects `sm_100a`, +`sm_103a` or `sm_107a` (operators with SM107 support) from the CUDA device of +the input tensor. Tensor-less AOT/offline builds use +`MM_SPARSE_TARGET_ARCH=100a|103a|107a` to select a target (default: `103a`). `TORCH_CUDA_ARCH_LIST` is internal compiler plumbing rather than the runtime architecture-selection interface. Q8KV4 Decode Attention, Decode Indexer, and the shared dequant package support CUDA Toolkit 12.9 or newer. They use QMUL4 when the selected toolchain supports it and otherwise select an exact fallback automatically. Q8KV4 Prefill Attention requires CUDA Toolkit -13.4 or newer. +13.4 or newer (13.5 or newer on SM107). BF16 and Q8KV8 sparse decode are provided through an optional external FlashInfer TRTLLM-GEN backend. This repository does not include FlashInfer source code or @@ -136,7 +136,7 @@ Q8KV4 decode uses native CUTLASS C++. All three decode attention formats support output on B200/B300, selecting the implementation by the actual `Hq/Hkv`. Q8KV4 decode also retains SM107 GQA=16 support, requiring CUDA Toolkit 13.5 or newer. -Rubin (SM107) retains BF16/Q8KV8 prefill attention, Q8KV8 prefill indexer, and Q8KV4 decode attention paths, +Rubin (SM107) retains BF16/Q8KV8/Q8KV4 prefill attention, Q8KV8 prefill indexer, and Q8KV4 decode attention paths, selected from the input tensor device. See the operator READMEs for dependencies and restrictions. This does not imply Rubin support for the other operators. diff --git a/README.zh-CN.md b/README.zh-CN.md index 8c19f6f2..6e2e7b93 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -112,12 +112,12 @@ python -c 'import cutlass; print(cutlass.__version__, cutlass.CUDA_VERSION)' ``` Q8KV4 C++ 算子使用标准的 `CUDA_HOME`、`CUTLASS_ROOT` 和 `TORCH_EXTENSIONS_DIR` -配置。运行时 JIT 始终根据输入 tensor 所在的 CUDA device 选择 `sm_100a` 或 -`sm_103a`;无 tensor 的 AOT/离线构建使用 `MM_SPARSE_TARGET_ARCH=100a|103a` 指定 -目标(默认 `103a`)。`TORCH_CUDA_ARCH_LIST` 只由内部编译流程设置,不作为运行时 +配置。运行时 JIT 始终根据输入 tensor 所在的 CUDA device 选择 `sm_100a`、 +`sm_103a` 或 `sm_107a`(支持 SM107 的算子);无 tensor 的 AOT/离线构建使用 +`MM_SPARSE_TARGET_ARCH=100a|103a|107a` 指定目标(默认 `103a`)。`TORCH_CUDA_ARCH_LIST` 只由内部编译流程设置,不作为运行时 架构选择接口。Q8KV4 Decode Attention、Decode Indexer 和共享 dequant 支持 CUDA Toolkit 12.9 或更高版本;工具链支持 QMUL4 时使用该路径,否则自动使用精确 -fallback。Q8KV4 Prefill Attention 要求 CUDA Toolkit 13.4 或更高版本。 +fallback。Q8KV4 Prefill Attention 要求 CUDA Toolkit 13.4 或更高版本(SM107 上要求 13.5 或更高版本)。 BF16 和 Q8KV8 sparse decode 通过可选的外部 FlashInfer TRTLLM-GEN backend 提供。本仓库不包含 FlashInfer 源码或 cubin;使用 `python -m pip install -e '.[flashinfer]'` 安装 @@ -125,7 +125,7 @@ FlashInfer 源码或 cubin;使用 `python -m pip install -e '.[flashinfer]'` 均支持 B200/B300 上的 GQA=8/16 和 BF16 输出,按实际 `Hq/Hkv` 选择实现。 Q8KV4 decode 另保留 SM107 的 GQA=16 支持,需要 CUDA Toolkit 13.5 或更新版本。 -Rubin(SM107)保留 BF16/Q8KV8 prefill attention、Q8KV8 prefill indexer 和 Q8KV4 decode attention 路径, +Rubin(SM107)保留 BF16/Q8KV8/Q8KV4 prefill attention、Q8KV8 prefill indexer 和 Q8KV4 decode attention 路径, 通过输入 tensor 所在设备自动选择;具体依赖和限制见各算子 README。其余算子不据此声明 Rubin 支持。 ## 3. 主要接口 diff --git a/benchmarks/inference/msa_v1/attention/prefill/q8kv4/benchmark.py b/benchmarks/inference/msa_v1/attention/prefill/q8kv4/benchmark.py index fc410549..e49fec26 100644 --- a/benchmarks/inference/msa_v1/attention/prefill/q8kv4/benchmark.py +++ b/benchmarks/inference/msa_v1/attention/prefill/q8kv4/benchmark.py @@ -371,8 +371,8 @@ def main() -> None: args = parser.parse_args() if args.slots < 0 or args.warmup < 1 or args.replays < 2: parser.error("slots must be non-negative, warmup positive, and replays >= 2") - if torch.cuda.get_device_capability() not in {(10, 0), (10, 3)}: - raise RuntimeError("SM100-family GPU (B200/GB300) required") + if torch.cuda.get_device_capability() not in {(10, 0), (10, 3), (10, 7)}: + raise RuntimeError("SM100, SM103 or SM107 GPU required") device = torch.device("cuda") _warm_compilation(device) diff --git a/inference/msa_v1/README.md b/inference/msa_v1/README.md index e7e2ae10..67ccd81c 100644 --- a/inference/msa_v1/README.md +++ b/inference/msa_v1/README.md @@ -32,7 +32,7 @@ Available formats and constraints: CUDA 13.5 or newer. - Q8KV8 prefill attention supports GQA group sizes 1, 2, 4, 8, and 16. -BF16/Q8KV8 prefill attention also retains SM107 Rubin paths selected by the actual device architecture. +BF16/Q8KV8/Q8KV4 prefill attention also retains SM107 Rubin paths selected by the actual device architecture. See the README in each operator directory for exact tensor shapes, dtypes, and usage examples. diff --git a/inference/msa_v1/README.zh-CN.md b/inference/msa_v1/README.zh-CN.md index 373e2a1b..ea7d8a1c 100644 --- a/inference/msa_v1/README.zh-CN.md +++ b/inference/msa_v1/README.zh-CN.md @@ -31,7 +31,7 @@ MSA v1 提供 paged sparse attention 和 indexer 的 decode/prefill 接口。所 Q8KV4 使用原生 CUTLASS C++,并保留 CUDA 13.5 或更新版本上的 SM107 GQA=16 支持。 - Q8KV8 prefill attention 支持 GQA group size 1、2、4、8 或 16。 -BF16/Q8KV8 prefill attention 还保留 SM107 Rubin 路径,由实际设备架构选择。 +BF16/Q8KV8/Q8KV4 prefill attention 还保留 SM107 Rubin 路径,由实际设备架构选择。 具体张量 shape、dtype 和调用示例见各算子目录中的 README。 diff --git a/inference/msa_v1/_build_utils.py b/inference/msa_v1/_build_utils.py index 2a1238b8..c2e86566 100644 --- a/inference/msa_v1/_build_utils.py +++ b/inference/msa_v1/_build_utils.py @@ -2,15 +2,35 @@ from __future__ import annotations +import fcntl +import hashlib +import logging import os import re import shutil import subprocess +from contextlib import contextmanager from functools import lru_cache from pathlib import Path +logger = logging.getLogger(__name__) + _REPOSITORY_ROOT = Path(__file__).resolve().parents[2] MM_SPARSE_TARGET_ARCH = "MM_SPARSE_TARGET_ARCH" +QMUL4_PROBE_SOURCE = r""" +#include + +__global__ void qmul4_probe(uint32_t* output) { + uint32_t result; + uint16_t packed_e2m1 = 0; + uint32_t scale_e4m3 = 0; + asm volatile( + "mul.rn.satfinite.e4m3x4.e2m1x4.e4m3x4 %0, %1, %2;" + : "=r"(result) + : "h"(packed_e2m1), "r"(scale_e4m3)); + output[0] = result; +} +""".lstrip() def normalize_target_arch( @@ -181,13 +201,90 @@ def cutlass_root() -> Path: ) +@contextmanager +def build_lock(cache_dir: Path): + """Keep a shared library immutable while another rank builds or loads it.""" + cache_dir.mkdir(parents=True, exist_ok=True) + with (cache_dir / "build.lock").open("a") as lock_file: + fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN) + + +def _write_text_if_changed(path: Path, content: str) -> None: + if path.is_file() and path.read_text(encoding="utf-8") == content: + return + path.write_text(content, encoding="utf-8") + + +def _probe_qmul4(nvcc: Path, arch: str, probe_dir: Path) -> bool: + result_path = probe_dir / "qmul4.result" + if result_path.is_file(): + return result_path.read_text(encoding="utf-8").strip() == "supported" + + probe_dir.mkdir(parents=True, exist_ok=True) + source_path = probe_dir / "qmul4_probe.cu" + object_path = probe_dir / f"qmul4_probe.{os.getpid()}.o" + _write_text_if_changed(source_path, QMUL4_PROBE_SOURCE) + result = subprocess.run( + [ + str(nvcc), + "-std=c++20", + f"-gencode=arch=compute_{arch},code=sm_{arch}", + "-c", + str(source_path), + "-o", + str(object_path), + ], + capture_output=True, + text=True, + check=False, + ) + supported = result.returncode == 0 + if supported: + object_path.unlink(missing_ok=True) + else: + logger.info( + "Selected NVCC does not accept QMUL4 for SM%s; using FP16 dequant fallback", + arch, + ) + _write_text_if_changed( + result_path, + "supported\n" if supported else "unsupported\n", + ) + return supported + + +def supports_qmul4(arch: str, *, probe_root: Path) -> bool: + """Return whether the selected NVCC accepts the public QMUL4 PTX form for ``arch``. + + The answer is recorded under ``probe_root`` per toolkit, architecture and probe source, so + every op that dequantizes NVFP4 shares one compile of the probe per toolchain. + """ + + nvcc = cuda_home() / "bin/nvcc" + probe_key = hashlib.sha256() + probe_key.update(str(nvcc.resolve()).encode()) + probe_key.update(str(cuda_version()).encode()) + probe_key.update(arch.encode()) + probe_key.update(QMUL4_PROBE_SOURCE.encode()) + probe_dir = probe_root / probe_key.hexdigest()[:16] + with build_lock(probe_dir): + return _probe_qmul4(nvcc, arch, probe_dir) + + __all__ = [ "MM_SPARSE_TARGET_ARCH", + "QMUL4_PROBE_SOURCE", + "build_lock", "cuda_home", "cuda_version", "cutlass_root", "normalize_target_arch", "require_cuda_version", + "supports_qmul4", "target_arch", "torch_cuda_arch", ] diff --git a/inference/msa_v1/attention/decode/q8kv4/jit.py b/inference/msa_v1/attention/decode/q8kv4/jit.py index a533d9ee..4ebbeae5 100644 --- a/inference/msa_v1/attention/decode/q8kv4/jit.py +++ b/inference/msa_v1/attention/decode/q8kv4/jit.py @@ -2,7 +2,6 @@ from __future__ import annotations -import fcntl import hashlib import logging import os @@ -10,16 +9,17 @@ import sys import threading import time -from contextlib import contextmanager from dataclasses import dataclass from functools import cache, lru_cache from pathlib import Path import jinja2 +from inference.msa_v1._build_utils import build_lock as _build_lock from inference.msa_v1._build_utils import cuda_home as _cuda_home from inference.msa_v1._build_utils import cutlass_root as _cutlass_root from inference.msa_v1._build_utils import require_cuda_version +from inference.msa_v1._build_utils import supports_qmul4 as _probe_supports_qmul4 from inference.msa_v1._build_utils import target_arch as _resolve_target_arch logger = logging.getLogger(__name__) @@ -35,20 +35,6 @@ } _QMUL4_DEQUANT = "qmul4" _FP16_DEQUANT = "fp16_fallback" -_QMUL4_PROBE_SOURCE = r""" -#include - -__global__ void qmul4_probe(uint32_t* output) { - uint32_t result; - uint16_t packed_e2m1 = 0; - uint32_t scale_e4m3 = 0; - asm volatile( - "mul.rn.satfinite.e4m3x4.e2m1x4.e4m3x4 %0, %1, %2;" - : "=r"(result) - : "h"(packed_e2m1), "r"(scale_e4m3)); - output[0] = result; -} -""".lstrip() def _write_text_if_changed(path: Path, content: str) -> None: @@ -57,18 +43,6 @@ def _write_text_if_changed(path: Path, content: str) -> None: path.write_text(content, encoding="utf-8") -@contextmanager -def _build_lock(cache_dir: Path): - """Keep a shared library immutable while another rank builds or loads it.""" - cache_dir.mkdir(parents=True, exist_ok=True) - with (cache_dir / "build.lock").open("a") as lock_file: - fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) - try: - yield - finally: - fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN) - - @lru_cache(maxsize=1) def _cuda_version() -> tuple[int, int]: return require_cuda_version( @@ -141,53 +115,7 @@ def _cache_root() -> Path: def _supports_qmul4(arch: str) -> bool: """Return whether the selected NVCC accepts the public QMUL4 PTX form.""" - nvcc = _cuda_home() / "bin/nvcc" - probe_key = hashlib.sha256() - probe_key.update(str(nvcc.resolve()).encode()) - probe_key.update(str(_cuda_version()).encode()) - probe_key.update(arch.encode()) - probe_key.update(_QMUL4_PROBE_SOURCE.encode()) - probe_dir = _cache_root() / "capability_probes" / probe_key.hexdigest()[:16] - with _build_lock(probe_dir): - return _probe_qmul4(nvcc, arch, probe_dir) - - -def _probe_qmul4(nvcc: Path, arch: str, probe_dir: Path) -> bool: - result_path = probe_dir / "qmul4.result" - if result_path.is_file(): - return result_path.read_text(encoding="utf-8").strip() == "supported" - - probe_dir.mkdir(parents=True, exist_ok=True) - source_path = probe_dir / "qmul4_probe.cu" - object_path = probe_dir / f"qmul4_probe.{os.getpid()}.o" - _write_text_if_changed(source_path, _QMUL4_PROBE_SOURCE) - result = subprocess.run( - [ - str(nvcc), - "-std=c++20", - f"-gencode=arch=compute_{arch},code=sm_{arch}", - "-c", - str(source_path), - "-o", - str(object_path), - ], - capture_output=True, - text=True, - check=False, - ) - supported = result.returncode == 0 - if supported: - object_path.unlink(missing_ok=True) - else: - logger.info( - "Selected NVCC does not accept QMUL4 for SM%s; using FP16 dequant fallback", - arch, - ) - _write_text_if_changed( - result_path, - "supported\n" if supported else "unsupported\n", - ) - return supported + return _probe_supports_qmul4(arch, probe_root=_cache_root() / "capability_probes") @cache diff --git a/inference/msa_v1/attention/prefill/_common/combine.py b/inference/msa_v1/attention/prefill/_common/combine.py index c4dae3f9..946ebb17 100644 --- a/inference/msa_v1/attention/prefill/_common/combine.py +++ b/inference/msa_v1/attention/prefill/_common/combine.py @@ -1,17 +1,20 @@ -"""Sparse forward combine kernel and public launcher. +"""Sparse prefill split combine (K2): merge the forward kernels' per-page partials. -The epilogue converts the partial-output STG.128 fake layout to the real -output-column order. +The sparse forward kernels write one partial output and one partial log-sum-exp per +(query, head, selected page); ``combine`` merges them into the final output and LSE through +``SparseAttentionForwardCombine``, a TMA-ring kernel over the flattened varlen rows. BF16/FP16 +partials and outputs only. """ +from __future__ import annotations + import math -from functools import partial +from dataclasses import dataclass from typing import Optional, Type import cutlass -from cutlass import Boolean, Float32, Int32, Int64, const_expr +from cutlass import Float32, Int32, Int64, const_expr import cutlass.cute as cute -from cutlass.cutlass_dsl import BaseDSL from cutlass.cute import FastDivmodDivisor from cutlass.cute.nvgpu import cpasync import cuda.bindings.driver as cuda @@ -19,229 +22,202 @@ from inference.msa_v1.attention.prefill._common.dsl import utils from inference.msa_v1.aot_cache import save_aot, try_load_aot -from inference.msa_v1.attention.prefill._common.dsl.compile_utils import compile_with_timing -from inference.msa_v1.attention.prefill._common.dsl.cute_dsl_utils import assume_tensor_aligned, torch2cute_dtype_map -from inference.msa_v1.attention.prefill._common.dsl.pack_gqa import PackGQAComb -from inference.msa_v1.attention.prefill._common.dsl.seqlen_info import SeqlenInfo -from inference.msa_v1.attention.prefill._common.dsl.tma_utils import stg128_half_fake_col_to_real_col +from inference.msa_v1.attention.prefill._common.dsl.compile_utils import ( + compile_with_timing, + make_fake_tensor, +) +from inference.msa_v1.attention.prefill._common.dsl.cute_dsl_utils import ( + assume_tensor_aligned, + torch2cute_dtype_map, +) + +# One tile is 64 flat (query, head) rows of 256 B, a 16 KB chunk per split; four slots keep +# 64 KB in flight per CTA and leave room for three CTAs per SM. +TILE_M = 64 +NUM_THREADS = 256 +STAGES = 4 +# Use a two-slot ring when the reads are not steered on SM107. Unsteered partials are +# interleaved across the memory locality domains, so half of each CTA's reads cross the +# inter-domain fabric, and on SM107 that fabric caps interleaved reads well below the local HBM +# rate. Keep in flight only what the fabric drains in one round trip: a deeper ring adds +# queueing that also delays the local half of the reads. Steered reads are domain-local and +# B200/B300 interleaved reads are HBM-bound, so both keep the four-slot ring. +STAGES_INTERLEAVED = 2 +# The partial buffer is addressed as (dim, flat row, split); the TMA descriptor lowering is +# relied on for split strides below this many elements. +MAX_SPLIT_SLAB_ELEMENTS = 2**31 + +_combine_compile_cache = {} + + +@dataclass(frozen=True) +class LocalityHints: + """Steer every CTA to the memory locality domain of its SM. + + ``sm_domains`` holds the locality domain of each SM id (``%smid``) as int32, -1 where unknown. + ``tile_counters`` holds one int32 per domain, the tile claims of a launch; they must be zero + when the launch starts (the forward kernel zeroes them for the combine that follows it). + ``page_bytes`` is the granularity at which the partial buffer alternates domains: page ``p`` + of every split slab lives in domain ``p % num_domains``, which a split stride that is a + multiple of ``num_domains * page_bytes`` keeps true for every slab. + """ + + sm_domains: torch.Tensor + tile_counters: torch.Tensor + page_bytes: int + + @property + def num_domains(self) -> int: + return int(self.tile_counters.numel()) class SparseAttentionForwardCombine: + """Merge the split partials of every (query, head) row through a TMA ring. + + The sparse forward kernels write one partial output and one partial log-sum-exp per + (query, head, selected page) into ``[num_splits, total_q, heads, dim]`` and + ``[num_splits, total_q, heads]`` buffers. This kernel merges the splits of every (query, head) + row into the final output and LSE. Rows are independent, so the concatenated varlen rows form + one flat scheduling domain: a CTA owns ``tile_m`` consecutive flat rows, which is one contiguous + chunk of each split's slab, and streams the chunks of its splits through a ring of ``stages`` + shared-memory slots with one bulk-tensor copy per (tile, split). + + The partial output columns are in the STG.128 "fake" order the forward epilogue stores (a 4x4 + transpose of 32-bit pairs inside each 32-column group); the epilogue here undoes it with two + XOR-shuffle stages before one coalesced 128-bit store per row. + + The split slabs of the partial buffer may be padded apart. On a GPU with several memory + locality domains (Rubin uGPU) the caller stripes the buffer so page ``p`` of every slab lives in + domain ``p % num_domains``, and hands the kernel the domain of every SM: a CTA then claims a tile + whose pages live in the domain of its own SM, from per-domain counters, and takes a tile of + another domain only once its own are gone. + """ + def __init__( self, dtype: Type[cutlass.Numeric], dtype_partial: Type[cutlass.Numeric], head_dim: int, - tile_m: int = 8, - k_block_size: int = 64, - topk: int = 16, - num_threads: int = 256, - stages: int = 4, + topk: int, + tile_m: int = TILE_M, + num_threads: int = NUM_THREADS, + stages: int = STAGES, use_pdl: bool = False, min_blocks_per_mp: int = 0, - raw_partial_stats: bool = False, + num_domains: int = 0, + lse_split_aligned: bool = True, ): + """Forward combine kernel for split attention computation. + + :param dtype: output data type (BF16 or F16) + :param dtype_partial: partial output data type (BF16 or F16) + :param head_dim: head dimension; a tile row is one head's ``head_dim`` elements + :param topk: exact number of split partials per row + :param tile_m: flat (query, head) rows per CTA + :param num_threads: threads per CTA + :param stages: ring slots of ``tile_m`` partial rows each + :param use_pdl: wait on the producer grid before reading its outputs + :param min_blocks_per_mp: CTAs per SM ptxas must leave registers for (0 lets it choose) + :param num_domains: memory locality domains the tiles are claimed by (0: tile = CTA index) + :param lse_split_aligned: the LSE partial slabs start 16-byte aligned (the flat row count is + a multiple of 4), so one 2-D bulk-tensor copy loads a tile's LSEs of every split; + otherwise the threads bring the tile in with 4-byte cp.async copies, since TMA needs + a 16-byte aligned split stride and box start """ - Forward combine kernel for split attention computation. - - :param dtype: output data type - :param dtype_partial: partial accumulation data type - :param head_dim: head dimension - :param tile_m: m block size - :param k_block_size: k block size - :param topk: exact number of split partials - :param num_threads: number of threads - :param stages: number of pipeline stages - """ + if dtype not in (cutlass.BFloat16, cutlass.Float16): + raise TypeError("the combine writes BF16 or F16 outputs") + if dtype_partial not in (cutlass.BFloat16, cutlass.Float16): + raise TypeError("the combine reads BF16 or F16 partials") + if not 1 <= topk <= 256: + raise ValueError(f"topk must be in [1, 256], got {topk}") + if num_threads % 32 != 0 or stages < 1: + raise ValueError("num_threads must be a multiple of 32 and stages at least 1") + if num_domains < 0 or num_domains == 1: + raise ValueError("num_domains must be 0 (no steering) or at least 2") + copy_bits = 128 + self.elems_per_copy = copy_bits // dtype_partial.width + if head_dim % self.elems_per_copy != 0: + raise ValueError("head_dim must be a multiple of one 16-byte copy") + # Threads that share one tile row, 16 bytes of it each. + self.threads_per_row = head_dim // self.elems_per_copy + if num_threads % self.threads_per_row != 0: + raise ValueError("num_threads must be a multiple of the threads per row") + self.rows_per_pass = num_threads // self.threads_per_row + if tile_m % self.rows_per_pass != 0: + raise ValueError("tile_m must be a multiple of the rows one pass covers") + # Threads that transpose one row of the LSE tile. + if num_threads % tile_m != 0: + raise ValueError("num_threads must be a multiple of tile_m") + self.lse_threads_per_row = num_threads // tile_m + if 32 % self.lse_threads_per_row != 0 or topk % self.lse_threads_per_row != 0: + raise ValueError("the threads per LSE row must divide the warp and the split count") self.dtype = dtype self.dtype_partial = dtype_partial self.head_dim = head_dim - self.tile_m = tile_m - self.k_block_size = k_block_size self.topk = topk + self.tile_m = tile_m self.num_threads = num_threads - self.is_even_k = head_dim % k_block_size == 0 + self.num_warps = num_threads // 32 self.stages = stages - arch = BaseDSL._get_dsl().get_arch_enum() - rubin_arch = getattr(arch.__class__, "sm_107", None) - self.is_rubin = rubin_arch is not None and arch.is_family_of(rubin_arch) self.use_pdl = use_pdl self.min_blocks_per_mp = min_blocks_per_mp - self.raw_partial_stats = raw_partial_stats - self.use_tma_partial = ( - raw_partial_stats - and dtype == cutlass.BFloat16 - and dtype_partial == cutlass.BFloat16 - and head_dim == 128 - and tile_m in (32, 64) - and k_block_size == 128 - and topk == 16 - and num_threads == tile_m * 4 - and stages == 2 - ) - - @staticmethod - def can_implement( - dtype, - dtype_partial, - head_dim, - tile_m, - k_block_size, - topk, - num_threads, - ) -> bool: - """Check if the kernel can be implemented with the given parameters.""" - if dtype not in [cutlass.Float16, cutlass.BFloat16, cutlass.Float32]: - return False - if dtype_partial not in [cutlass.Float16, cutlass.BFloat16]: - return False - if head_dim % 8 != 0: - return False - if num_threads % 32 != 0: - return False - if tile_m % 8 != 0: - return False - if topk > 256: - return False - if (tile_m * topk) % num_threads != 0: - return False - return True + self.num_domains = num_domains + self.lse_split_aligned = lse_split_aligned def _setup_attributes(self): - # GMEM copy setup for O partial - universal_copy_bits = 128 - async_copy_elems = universal_copy_bits // self.dtype_partial.width - assert self.k_block_size % async_copy_elems == 0 - - k_block_gmem = ( - 128 if self.k_block_size % 128 == 0 else (64 if self.k_block_size % 64 == 0 else 32) - ) - gmem_threads_per_row = k_block_gmem // async_copy_elems - assert self.num_threads % gmem_threads_per_row == 0 - - # Async copy atom for O partial load - atom_async_copy_partial = cute.make_copy_atom( - cpasync.CopyG2SOp(cache_mode=cpasync.LoadCacheMode.GLOBAL), - self.dtype_partial, - num_bits_per_copy=universal_copy_bits, - ) - tOpartial_layout = cute.make_ordered_layout( - (self.num_threads // gmem_threads_per_row, gmem_threads_per_row), - order=(1, 0), - ) - vOpartial_layout = cute.make_layout((1, async_copy_elems)) - self.gmem_tiled_copy_O_partial = cute.make_tiled_copy_tv( - atom_async_copy_partial, tOpartial_layout, vOpartial_layout - ) - - # GMEM copy setup for final O (use universal copy for store). - # Keep output stores independent from the partial-load copy atom. - output_copy_elems = universal_copy_bits // self.dtype.width - assert self.k_block_size % output_copy_elems == 0 - gmem_threads_per_row_o = k_block_gmem // output_copy_elems - assert self.num_threads % gmem_threads_per_row_o == 0 - atom_universal_copy = cute.make_copy_atom( - cute.nvgpu.CopyUniversalOp(), - self.dtype, - num_bits_per_copy=universal_copy_bits, - ) - tO_layout = cute.make_ordered_layout( - (self.num_threads // gmem_threads_per_row_o, gmem_threads_per_row_o), - order=(1, 0), - ) - vO_layout = cute.make_layout((1, output_copy_elems)) - self.gmem_tiled_copy_O = cute.make_tiled_copy_tv( - atom_universal_copy, - tO_layout, - vO_layout, - ) - # LSE copy setup with async copy (alignment = 1) - lse_copy_bits = Float32.width # 1 element per copy, width is in bits - m_block_smem = ( - 128 - if self.tile_m % 128 == 0 - else ( - 64 - if self.tile_m % 64 == 0 - else (32 if self.tile_m % 32 == 0 else (16 if self.tile_m % 16 == 0 else 8)) - ) - ) - gmem_threads_per_row_lse = m_block_smem - assert self.num_threads % gmem_threads_per_row_lse == 0 - - # Async copy atom for LSE load - atom_async_copy_lse = cute.make_copy_atom( - cpasync.CopyG2SOp(cache_mode=cpasync.LoadCacheMode.ALWAYS), - Float32, - num_bits_per_copy=lse_copy_bits, - ) - tLSE_layout = cute.make_ordered_layout( - (self.num_threads // gmem_threads_per_row_lse, gmem_threads_per_row_lse), - order=(1, 0), + copy_bits = 128 + # One thread map serves the reads of a ring slot and the output stores: BF16 and F16 + # have the same width, so a thread's 16 bytes cover the same columns in both. + thr_layout = cute.make_ordered_layout( + (self.rows_per_pass, self.threads_per_row), order=(1, 0) + ) + val_layout = cute.make_layout((1, self.elems_per_copy)) + self.tiled_copy_partial = cute.make_tiled_copy_tv( + cute.make_copy_atom( + cute.nvgpu.CopyUniversalOp(), self.dtype_partial, num_bits_per_copy=copy_bits + ), + thr_layout, + val_layout, + ) + self.tiled_copy_out = cute.make_tiled_copy_tv( + cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), self.dtype, num_bits_per_copy=copy_bits), + thr_layout, + val_layout, + ) + # LSE tile (split, row): consecutive lanes transpose the splits of one row. + s2r_thr_layout = cute.make_ordered_layout( + (self.lse_threads_per_row, self.tile_m), order=(0, 1) + ) + self.s2r_tiled_copy_lse = cute.make_tiled_copy_tv( + cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Float32), + s2r_thr_layout, + cute.make_layout(1), ) - vLSE_layout = cute.make_layout(1) - self.gmem_tiled_copy_LSE = cute.make_tiled_copy_tv( - atom_async_copy_lse, tLSE_layout, vLSE_layout + # Unaligned LSE slabs: every thread brings topk / lse_threads_per_row splits of one row in + # with 4-byte cp.async copies; consecutive threads take consecutive rows of a split. + g2s_thr_layout = cute.make_ordered_layout( + (self.tile_m, self.lse_threads_per_row), order=(0, 1) ) - - # /////////////////////////////////////////////////////////////////////////////// - # Shared memory - # /////////////////////////////////////////////////////////////////////////////// - - # Shared memory to register copy for LSE - self.smem_threads_per_col_lse = self.num_threads // m_block_smem - assert 32 % self.smem_threads_per_col_lse == 0 # Must divide warp size - - s2r_layout_atom_lse = cute.make_ordered_layout( - (self.smem_threads_per_col_lse, self.num_threads // self.smem_threads_per_col_lse), - order=(0, 1), + self.g2s_tiled_copy_lse = cute.make_tiled_copy_tv( + cute.make_copy_atom(cpasync.CopyG2SOp(), Float32, num_bits_per_copy=Float32.width), + g2s_thr_layout, + cute.make_layout((1, self.topk // self.lse_threads_per_row)), ) - self.s2r_tiled_copy_LSE = cute.make_tiled_copy_tv( - cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Float32), - s2r_layout_atom_lse, - cute.make_layout(1), + # The bulk copy writes the tile as a (row, split) box over the same bytes; the trailing + # mode is the single stage the TMA partition idiom expects. + self.smem_layout_lse = cute.make_ordered_layout((self.topk, self.tile_m), order=(1, 0)) + self.smem_layout_lse_tma = cute.make_ordered_layout( + (self.tile_m, self.topk, 1), order=(0, 1, 2) ) - - # LSE shared memory layout with swizzling to avoid bank conflicts - # This works for kBlockMSmem = 8, 16, 32, 64, 128, no bank conflicts - if const_expr(m_block_smem == 8): - smem_lse_swizzle = cute.make_swizzle(5, 0, 5) - elif const_expr(m_block_smem == 16): - smem_lse_swizzle = cute.make_swizzle(4, 0, 4) - else: - smem_lse_swizzle = cute.make_swizzle(3, 2, 3) - lse_atom_splits = min(self.topk, 8) - smem_layout_atom_lse = cute.make_composed_layout( - smem_lse_swizzle, - 0, - cute.make_ordered_layout((lse_atom_splits, m_block_smem), order=(1, 0)), + # Ring slot: row-major (row, dim); 16 threads read 16 B each of one 256 B row, which is + # conflict-free without a swizzle. The TMA view is its (dim, row) transpose. + self.smem_layout_o = cute.make_ordered_layout( + (self.tile_m, self.head_dim, self.stages), order=(1, 0, 2) ) - self.smem_layout_lse = cute.tile_to_shape( - smem_layout_atom_lse, (self.topk, self.tile_m), (0, 1) + self.smem_layout_o_tma = cute.make_ordered_layout( + (self.head_dim, self.tile_m, self.stages), order=(0, 1, 2) ) - # O_partial staging layout. The target raw-BF16 specialization uses a - # row-major tile that is shared by the TMA and consumer-thread views. - if const_expr(self.use_tma_partial): - self.smem_layout_o = cute.make_ordered_layout( - (self.tile_m, self.k_block_size, self.stages), - order=(1, 0, 2), - ) - self.smem_layout_o_tma = cute.make_ordered_layout( - (self.k_block_size, self.tile_m, self.stages), - order=(0, 1, 2), - ) - else: - smem_layout_atom_o = _get_cpasync_smem_layout_atom( - self.dtype_partial, self.k_block_size - ) - self.smem_layout_o = cute.tile_to_shape( - smem_layout_atom_o, - (self.tile_m, self.k_block_size, self.stages), - (0, 1, 2), - ) - self.smem_layout_o_tma = None - @cute.jit def __call__( self, @@ -249,667 +225,414 @@ def __call__( mLSE_partial: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor] = None, - mLSE_temperature_partial: Optional[cute.Tensor] = None, - mLSE_temperature: Optional[cute.Tensor] = None, - cu_seqlens: Optional[cute.Tensor] = None, - seqused: Optional[cute.Tensor] = None, - num_splits_dynamic_ptr: Optional[cute.Tensor] = None, - varlen_batch_idx: Optional[cute.Tensor] = None, - semaphore_to_reset: Optional[cute.Tensor] = None, mSplitCounts: Optional[cute.Tensor] = None, - mOutputScale: Optional[cute.Tensor] = None, qhead_per_kvhead: Int32 = Int32(1), + mSmDomains: Optional[cute.Tensor] = None, + mTileCounters: Optional[cute.Tensor] = None, + tiles_per_page_log2: Int32 = Int32(0), # Always keep stream as the last parameter (EnvStream: obtained implicitly via TVM FFI). stream: cuda.CUstream = None, ): - # Type checking - if const_expr(not (mO_partial.element_type == self.dtype_partial)): + if const_expr(mO_partial.element_type != self.dtype_partial): raise TypeError("O partial tensor must match dtype_partial") - if const_expr(not (mO.element_type == self.dtype)): + if const_expr(mO.element_type != self.dtype): raise TypeError("O tensor must match dtype") - if const_expr(mLSE_partial.element_type not in [Float32]): + if const_expr(mLSE_partial.element_type != Float32): raise TypeError("LSE partial tensor must be Float32") - if const_expr(mLSE is not None and mLSE.element_type not in [Float32]): + if const_expr(mLSE is not None and mLSE.element_type != Float32): raise TypeError("LSE tensor must be Float32") - if const_expr( - mLSE_temperature_partial is not None - and mLSE_temperature_partial.element_type not in [Float32] - ): - raise TypeError("temperature LSE partial tensor must be Float32") - if const_expr(mLSE_temperature is not None and mLSE_temperature.element_type not in [Float32]): - raise TypeError("temperature LSE tensor must be Float32") - if const_expr((mLSE_temperature_partial is None) != (mLSE_temperature is None)): - raise ValueError( - "temperature LSE partial and output tensors must either both be provided or both be None" - ) - - # Shape validation - input tensors are in user format, need to be converted to kernel format - if const_expr(len(mO_partial.shape) not in [4, 5]): - raise ValueError( - "O partial tensor must have 4 or 5 dimensions: (num_splits, batch, seqlen, nheads, headdim) or (num_splits, total_q, nheads, headdim)" - ) - if const_expr(self.raw_partial_stats): - if const_expr(len(mLSE_partial.shape) != 4): - raise ValueError( - "Raw partial stats must have shape " - "(num_splits, total_q, nheads, 2)" - ) - if const_expr(cu_seqlens is None): - raise ValueError("Raw partial stats currently require the varlen combine path") - if const_expr(mLSE_temperature_partial is not None): - raise ValueError("Raw partial stats do not support independent temperature LSE") - elif const_expr(len(mLSE_partial.shape) not in [3, 4]): - raise ValueError( - "LSE partial tensor must have 3 or 4 dimensions: (num_splits, batch, seqlen, nheads) or (num_splits, total_q, nheads)" - ) - if const_expr(len(mO.shape) not in [3, 4]): - raise ValueError( - "O tensor must have 3 or 4 dimensions: (batch, seqlen, nheads, headdim) or (total_q, nheads, headdim)" - ) - if const_expr(mLSE is not None and len(mLSE.shape) not in [2, 3]): - raise ValueError( - "LSE tensor must have 2 or 3 dimensions: (batch, seqlen, nheads) or (total_q, nheads)" - ) - if const_expr(mLSE_temperature_partial is not None and len(mLSE_temperature_partial.shape) not in [3, 4]): - raise ValueError( - "temperature LSE partial tensor must have 3 or 4 dimensions: " - "(num_splits, batch, seqlen, nheads) or (num_splits, total_q, nheads)" - ) - if const_expr(mLSE_temperature is not None and len(mLSE_temperature.shape) not in [2, 3]): - raise ValueError( - "temperature LSE tensor must have 2 or 3 dimensions: " - "(batch, seqlen, nheads) or (total_q, nheads)" - ) + if const_expr(len(mO_partial.shape) != 4): + raise ValueError("O partial tensor must be (num_splits, total_q, nheads, headdim)") + if const_expr(len(mLSE_partial.shape) != 3): + raise ValueError("LSE partial tensor must be (num_splits, total_q, nheads)") + if const_expr(len(mO.shape) != 3): + raise ValueError("O tensor must be (total_q, nheads, headdim)") + if const_expr(mLSE is not None and len(mLSE.shape) != 2): + raise ValueError("LSE tensor must be (total_q, nheads)") if const_expr(mSplitCounts is not None): - if const_expr(mSplitCounts.element_type not in [Int32]): + if const_expr(mSplitCounts.element_type != Int32): raise TypeError("split_counts tensor must be Int32") - if const_expr(cu_seqlens is not None): - if const_expr(len(mSplitCounts.shape) != 2): - raise ValueError("varlen split_counts tensor must have shape (total_q, nheads_kv)") - elif const_expr(len(mSplitCounts.shape) != 3): - raise ValueError("batched split_counts tensor must have shape (batch, seqlen, nheads_kv)") - if const_expr(mOutputScale is not None and mOutputScale.element_type not in [Float32]): - raise TypeError("output_scale tensor must be Float32") + if const_expr(len(mSplitCounts.shape) != 2): + raise ValueError("split_counts tensor must be (total_q, nheads_kv)") + if const_expr((mSmDomains is None) != (mTileCounters is None)): + raise ValueError("sm_domains and tile_counters must either both be provided or both be None") + if const_expr((mTileCounters is not None) != (self.num_domains > 0)): + raise ValueError("tile_counters are required exactly when num_domains is set") + if const_expr( + mTileCounters is not None + and (mSmDomains.element_type != Int32 or mTileCounters.element_type != Int32) + ): + raise TypeError("sm_domains and tile_counters must be Int32") mO_partial, mO = [assume_tensor_aligned(t) for t in (mO_partial, mO)] - # (num_splits, b, seqlen, h, d) -> (seqlen, d, num_splits, h, b) - # or (num_splits, total_q, h, d) -> (total_q, d, num_splits, h) - O_partial_layout_transpose = ( - [2, 4, 0, 3, 1] if const_expr(cu_seqlens is None) else [1, 3, 0, 2] - ) - # (b, seqlen, h, d) -> (seqlen, d, h, b) or (total_q, h, d) -> (total_q, d, h) - mO_partial = cute.make_tensor( - mO_partial.iterator, cute.select(mO_partial.layout, mode=O_partial_layout_transpose) - ) - O_layout_transpose = [1, 3, 2, 0] if const_expr(cu_seqlens is None) else [0, 2, 1] - mO = cute.make_tensor(mO.iterator, cute.select(mO.layout, mode=O_layout_transpose)) - # (num_splits, b, h, seqlen) -> (seqlen, num_splits, h, b) - # Input is pre-transposed: [topK, B, Hq, Sq] with Sq innermost for K2-friendly reads. - # or (num_splits, total_q, h) -> (total_q, num_splits, h) - LSE_partial_layout_transpose = [3, 0, 2, 1] if const_expr(cu_seqlens is None) else [1, 0, 2] - mRawStats = None - mRowSum_partial = None - if const_expr(self.raw_partial_stats): - # [split, q, head, stat] -> [q, split, head, stat]. Keep the - # interleaved pair ABI while exposing scalar component views to K2. - mPartialStats = cute.make_tensor( - mLSE_partial.iterator, - cute.select(mLSE_partial.layout, mode=[1, 0, 2, 3]), - ) - mRawStats = mPartialStats - mLSE_partial = mPartialStats[None, None, None, 0] - mRowSum_partial = mPartialStats[None, None, None, 1] - else: - mLSE_partial = cute.make_tensor( - mLSE_partial.iterator, - cute.select(mLSE_partial.layout, mode=LSE_partial_layout_transpose), - ) - # (b, seqlen, h) -> (seqlen, h, b) or (total_q, h) -> (total_q, h) - LSE_layout_transpose = [1, 2, 0] if const_expr(cu_seqlens is None) else [0, 1] - mLSE = ( - cute.make_tensor(mLSE.iterator, cute.select(mLSE.layout, mode=LSE_layout_transpose)) - if mLSE is not None - else None - ) - mLSE_temperature_partial = ( - cute.make_tensor( - mLSE_temperature_partial.iterator, - cute.select(mLSE_temperature_partial.layout, mode=LSE_partial_layout_transpose), - ) - if mLSE_temperature_partial is not None - else None - ) - mLSE_temperature = ( - cute.make_tensor( - mLSE_temperature.iterator, - cute.select(mLSE_temperature.layout, mode=LSE_layout_transpose), - ) - if mLSE_temperature is not None - else None - ) - - # Determine if we have variable length sequences - varlen = const_expr(cu_seqlens is not None or seqused is not None) - + num_head = mO_partial.shape[2] + total_flat = mO_partial.shape[1] * num_head self._setup_attributes() - # Flatten [split, q, head] into one TMA row coordinate, matching the - # CUDA combine descriptor. A separate split mode would require a - # D * total_q * heads stride; that stride reaches exactly 2**32 - # elements for the 512K target and wraps them in a CuTe DSL descriptor - # lowering. The flattened row extent remains representable and keeps - # every 32x128 transfer contiguous. - tma_atom_O_partial = None - mO_partial_tma = None - if const_expr(self.use_tma_partial): - total_flat = mO_partial.shape[0] * mO_partial.shape[3] - mO_partial_tma = cute.make_tensor( - mO_partial.iterator, - cute.make_layout( - (self.k_block_size, total_flat * self.topk), - stride=( - 1, - self.k_block_size, - ), - ), - ) - tma_atom_O_partial, mO_partial_tma = cpasync.make_tiled_tma_atom( - cpasync.CopyBulkTensorTileG2SOp(), - mO_partial_tma, - cute.select(self.smem_layout_o_tma, mode=[0, 1]), - (self.k_block_size, self.tile_m), - ) - - raw_stats_copy_atom = None - if const_expr(self.use_tma_partial): - raw_stats_copy_atom = cute.make_copy_atom( - cute.nvgpu.CopyUniversalOp(), - Float32, - num_bits_per_copy=64, - ) - - smem_layout_lse_aux = ( - cute.make_layout((1,), stride=(1,)) - if const_expr(self.use_tma_partial) - else self.smem_layout_lse + # (num_splits, total_q, nheads, headdim) with contiguous slabs as (headdim, flat row, + # split): a (headdim, tile_m) box is one tile of one split. The slabs keep their own + # stride, which may be padded. + mO_partial_tma = cute.make_tensor( + mO_partial.iterator, + cute.make_layout( + (self.head_dim, total_flat, self.topk), + stride=(1, self.head_dim, mO_partial.stride[0]), + ), + ) + tma_atom_O_partial, mO_partial_tma = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileG2SOp(), + mO_partial_tma, + cute.select(self.smem_layout_o_tma, mode=[0, 1]), + (self.head_dim, self.tile_m), ) + num_m_blocks = cute.ceil_div(total_flat, self.tile_m) - # BF16/F16 output uses the register-shuffle epilogue and does not need - # the legacy shared-memory permutation buffer. Keep a one-element - # placeholder so one SharedStorage type can serve all specializations. - if const_expr(self.dtype in [cutlass.Float16, cutlass.BFloat16]): - smem_layout_perm = cute.make_layout((1,), stride=(1,)) - else: - smem_layout_perm = cute.make_ordered_layout( - (self.tile_m, self.k_block_size), order=(1, 0) + # The contiguous (num_splits, total_q, nheads) LSE partials as (flat row, split). With + # aligned slabs, a TMA atom whose (tile_m, num_splits) box is a CTA's whole LSE tile and + # its coordinate tensor; otherwise no atom and the plain view, which the threads copy + # with cp.async (TMA rejects a split stride or a box start that is not 16-byte aligned). + mLSE_2d = cute.make_tensor( + mLSE_partial.iterator, + cute.make_layout((total_flat, self.topk), stride=(1, total_flat)), + ) + if const_expr(self.lse_split_aligned): + tma_atom_LSE, mLSE_partial_tma = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileG2SOp(), + mLSE_2d, + cute.select(self.smem_layout_lse_tma, mode=[0, 1]), + (self.tile_m, self.topk), ) + else: + tma_atom_LSE, mLSE_partial_tma = None, mLSE_2d + + lse_tile_elems = cute.cosize(self.smem_layout_lse) @cute.struct class SharedStorage: - sLSE: cute.struct.Align[ - cute.struct.MemRange[Float32, cute.cosize(self.smem_layout_lse)], 128 + sLSE: cute.struct.Align[cute.struct.MemRange[Float32, lse_tile_elems], 128] + sBlockMaxValidSplit: cute.struct.Align[ + cute.struct.MemRange[Int32, self.num_warps], 128 ] - sLSETemperature: cute.struct.Align[ - cute.struct.MemRange[Float32, cute.cosize(smem_layout_lse_aux)], 128 - ] - sMaxValidSplit: cute.struct.Align[cute.struct.MemRange[Int32, self.tile_m], 128] sO: cute.struct.Align[ cute.struct.MemRange[self.dtype_partial, cute.cosize(self.smem_layout_o)], 128 ] - sO_perm: cute.struct.Align[ - cute.struct.MemRange[self.dtype, cute.cosize(smem_layout_perm)], 128 - ] - sOTmaMbar: cute.struct.Align[ - cute.struct.MemRange[Int64, self.stages], 128 - ] - smem_size = SharedStorage.size_in_bytes() + sRingMbar: cute.struct.Align[cute.struct.MemRange[Int64, self.stages], 8] + sLseMbar: cute.struct.Align[cute.struct.MemRange[Int64, 1], 8] + sTile: cute.struct.Align[cute.struct.MemRange[Int32, 1], 8] - @cute.struct - class TmaRawSharedStorage: - sOTmaMbar: cute.struct.Align[ - cute.struct.MemRange[Int64, self.stages], 128 - ] - sLSE: cute.struct.Align[ - cute.struct.MemRange[Float32, cute.cosize(self.smem_layout_lse)], 128 - ] - sMaxValidSplit: cute.struct.Align[ - cute.struct.MemRange[Int32, self.tile_m], 128 - ] - sO: cute.struct.Align[ - cute.struct.MemRange[ - self.dtype_partial, - cute.cosize(self.smem_layout_o), - ], - 128, - ] - tma_raw_smem_size = TmaRawSharedStorage.size_in_bytes() - - # Flatten concatenated varlen rows into one scheduling domain. Each - # combine row is independent, so this preserves the varlen layout - # while avoiding one total_q-sized grid per batch. - flatten_varlen = const_expr( - cu_seqlens is not None - and seqused is None - and varlen_batch_idx is None - ) - - # Grid: (ceil(rows * heads / tile_m), ceil(dim / k_block), domains) - # Head separated from rows enables future TMA on contiguous row tiles. - seqlen = mO_partial.shape[0] - num_head = mO_partial.shape[3] - batch_size = ( - Int32(1) - if const_expr(flatten_varlen) - else ( - mO_partial.shape[4] - if const_expr(cu_seqlens is None) - else Int32(cu_seqlens.shape[0] - 1) - ) - ) - - seqlen_divmod = FastDivmodDivisor(seqlen) - head_divmod = FastDivmodDivisor(num_head) - - grid_dim = ( - cute.ceil_div(seqlen * num_head, self.tile_m), - cute.ceil_div(self.head_dim, self.k_block_size), - batch_size, + grid_dim = (num_m_blocks, 1, 1) + self.kernel( + mO_partial_tma, + mLSE_partial_tma, + mO, + mLSE, + mSplitCounts, + qhead_per_kvhead, + mSmDomains, + mTileCounters, + tiles_per_page_log2, + tma_atom_O_partial, + tma_atom_LSE, + SharedStorage, + self.smem_layout_lse, + self.smem_layout_lse_tma, + self.smem_layout_o, + self.smem_layout_o_tma, + self.tiled_copy_partial, + self.tiled_copy_out, + self.s2r_tiled_copy_lse, + self.g2s_tiled_copy_lse, + FastDivmodDivisor(num_head), + self.use_pdl, + ).launch( + grid=grid_dim, + block=[self.num_threads, 1, 1], + smem=SharedStorage.size_in_bytes(), + stream=stream, + min_blocks_per_mp=self.min_blocks_per_mp, + use_pdl=self.use_pdl, ) - if const_expr(self.use_tma_partial): - if const_expr(not flatten_varlen): - raise ValueError("TMA raw combine requires flattened varlen tensors") - self.kernel_tma_raw( - mO_partial_tma, - mRawStats, - mO, - mLSE, - semaphore_to_reset, - mSplitCounts, - mOutputScale, - qhead_per_kvhead, - tma_atom_O_partial, - raw_stats_copy_atom, - TmaRawSharedStorage, - self.smem_layout_lse, - self.smem_layout_o, - self.smem_layout_o_tma, - self.gmem_tiled_copy_O_partial, - self.gmem_tiled_copy_O, - head_divmod, - self.use_pdl, - ).launch( - grid=grid_dim, - block=[self.num_threads, 1, 1], - smem=tma_raw_smem_size, - stream=stream, - min_blocks_per_mp=self.min_blocks_per_mp, - use_pdl=self.use_pdl, - ) - else: - self.kernel( - mO_partial, - mO_partial_tma, - mLSE_partial, - mRowSum_partial, - mRawStats, - mO, - mLSE, - mLSE_temperature_partial, - mLSE_temperature, - cu_seqlens, - seqused, - num_splits_dynamic_ptr, - varlen_batch_idx, - semaphore_to_reset, - mSplitCounts, - mOutputScale, - qhead_per_kvhead, - tma_atom_O_partial, - raw_stats_copy_atom, - SharedStorage, - self.smem_layout_lse, - smem_layout_lse_aux, - self.smem_layout_o, - self.smem_layout_o_tma, - smem_layout_perm, - self.gmem_tiled_copy_O_partial, - self.gmem_tiled_copy_O, - self.gmem_tiled_copy_LSE, - self.s2r_tiled_copy_LSE, - seqlen_divmod, - head_divmod, - self.use_pdl, - varlen, - flatten_varlen, - ).launch( - grid=grid_dim, - block=[self.num_threads, 1, 1], - smem=smem_size, - stream=stream, - min_blocks_per_mp=self.min_blocks_per_mp, - use_pdl=self.use_pdl, - ) - - @cute.jit - def decode_flat_row_idx( - self, - idx: Int32, - head_divmod: FastDivmodDivisor, - ): - """Decode flattened tile rows under the H_q-innermost contract.""" - q_idx_local, head_idx = divmod(idx, head_divmod) - return q_idx_local, head_idx - @cute.kernel - def kernel_tma_raw( + def kernel( self, mO_partial_tma: cute.Tensor, - mRawStats: cute.Tensor, + mLSE_partial_tma: cute.Tensor, mO: cute.Tensor, mLSE: Optional[cute.Tensor], - semaphore_to_reset: Optional[cute.Tensor], mSplitCounts: Optional[cute.Tensor], - mOutputScale: Optional[cute.Tensor], qhead_per_kvhead: Int32, + mSmDomains: Optional[cute.Tensor], + mTileCounters: Optional[cute.Tensor], + tiles_per_page_log2: Int32, tma_atom_O_partial: cute.CopyAtom, - raw_stats_copy_atom: cute.CopyAtom, + tma_atom_LSE: Optional[cute.CopyAtom], SharedStorage: cutlass.Constexpr, - smem_layout_lse: cute.Layout | cute.ComposedLayout, - smem_layout_o: cute.Layout | cute.ComposedLayout, + smem_layout_lse: cute.Layout, + smem_layout_lse_tma: cute.Layout, + smem_layout_o: cute.Layout, smem_layout_o_tma: cute.Layout, - gmem_tiled_copy_O_partial: cute.TiledCopy, - gmem_tiled_copy_O: cute.TiledCopy, + tiled_copy_partial: cute.TiledCopy, + tiled_copy_out: cute.TiledCopy, + s2r_tiled_copy_lse: cute.TiledCopy, + g2s_tiled_copy_lse: cute.TiledCopy, head_divmod: FastDivmodDivisor, use_pdl: cutlass.Constexpr[bool], ): - """CUDA-shaped raw-stat combine specialization for the SM100 target.""" tidx, _, _ = cute.arch.thread_idx() warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) - m_block, k_block, maybe_virtual_batch = cute.arch.block_idx() - - if const_expr(use_pdl and semaphore_to_reset is not None): - if ( - tidx == 0 - and m_block == cute.arch.grid_dim()[0] - 1 - and k_block == cute.arch.grid_dim()[1] - 1 - and maybe_virtual_batch == cute.arch.grid_dim()[2] - 1 - ): - cute.arch.griddepcontrol_wait() - semaphore_to_reset[0] = 0 - if const_expr(use_pdl): - cute.arch.griddepcontrol_wait() + m_block, _, _ = cute.arch.block_idx() + total_tiles, _, _ = cute.arch.grid_dim() + total_flat = mO.shape[0] * mO.shape[1] + steer_tiles = const_expr(mTileCounters is not None) smem = cutlass.utils.SmemAllocator() storage = smem.allocate(SharedStorage) sLSE = storage.sLSE.get_tensor(smem_layout_lse) - sMaxValidSplit = storage.sMaxValidSplit.get_tensor((self.tile_m,)) + sLSE_tma = storage.sLSE.get_tensor(smem_layout_lse_tma) + sBlockMaxValidSplit = storage.sBlockMaxValidSplit.get_tensor((self.num_warps,)) sO = storage.sO.get_tensor(smem_layout_o) sO_tma = storage.sO.get_tensor(smem_layout_o_tma) - sO_tma_mbar_ptr = storage.sOTmaMbar.data_ptr() + ring_mbar = storage.sRingMbar.data_ptr() + lse_mbar = storage.sLseMbar.data_ptr() + sTile = storage.sTile.get_tensor((1,)) - total_flat = mRawStats.shape[0] * mRawStats.shape[2] + # Barriers are CTA-local state, and the tile claim depends on nothing the producer grid + # writes (it zeroed the counters at its start): both happen while that grid is still + # draining. + if tidx == 0: + for stage in cutlass.range(self.stages, unroll_full=True): + cute.arch.mbarrier_init(ring_mbar + stage, 1) + cute.arch.mbarrier_init(lse_mbar, 1 if self.lse_split_aligned else self.num_threads) + cute.arch.mbarrier_init_fence() + if const_expr(steer_tiles): + sTile[0] = self.claim_tile( + mSmDomains, mTileCounters, total_tiles, tiles_per_page_log2 + ) + cute.arch.sync_threads() + if const_expr(steer_tiles): + m_block = sTile[0] tile_begin = m_block * self.tile_m - output_scale = Float32(1.0) - if const_expr(mOutputScale is not None): - output_scale = mOutputScale[0] + if const_expr(use_pdl): + cute.arch.griddepcontrol_wait() - # Initialize the two transaction barriers and overlap the initial TMA - # loads with raw-stat reduction, matching the CUDA schedule. - gO_partial_tma = cute.local_tile( - mO_partial_tma, - (self.k_block_size, self.tile_m), - (k_block, None), + # This CTA's tile of every split, and its LSE tile. + gO_partial = cute.local_tile( + mO_partial_tma, (self.head_dim, self.tile_m), (0, None, None) ) tOsO_tma, tOgO_tma = cpasync.tma_partition( tma_atom_O_partial, 0, cute.make_layout(1), cute.group_modes(sO_tma, 0, 2), - cute.group_modes(gO_partial_tma, 0, 2), - ) - o_tma_copy_bytes = const_expr( - cute.size_in_bytes( - self.dtype_partial, - cute.select(smem_layout_o_tma, mode=[0, 1]), + cute.group_modes(gO_partial, 0, 2), + ) + o_tma_bytes = const_expr( + cute.size_in_bytes(self.dtype_partial, cute.select(smem_layout_o_tma, mode=[0, 1])) + ) + # The LSE tile: with aligned slabs one (tile_m, num_splits) TMA box per tile; otherwise + # 4-byte cp.async copies by every thread into the same smem bytes, completing the same + # barrier with one arrive per thread. + if const_expr(self.lse_split_aligned): + gLSE = cute.local_tile(mLSE_partial_tma, (self.tile_m, self.topk), (None, 0)) + tLSEsLSE_tma, tLSEgLSE_tma = cpasync.tma_partition( + tma_atom_LSE, + 0, + cute.make_layout(1), + cute.group_modes(sLSE_tma, 0, 2), + cute.group_modes(gLSE, 0, 2), + ) + lse_tma_bytes = const_expr( + cute.size_in_bytes(Float32, cute.select(smem_layout_lse_tma, mode=[0, 1])) ) - ) - row_tiles_per_split = total_flat // Int32(self.tile_m) - if tidx == 0: - for stage in cutlass.range(self.stages, unroll_full=True): - cute.arch.mbarrier_init(sO_tma_mbar_ptr + stage, 1) - cute.arch.mbarrier_init_fence() - cute.arch.sync_threads() + else: + g2s_thr_copy_lse = g2s_tiled_copy_lse.get_slice(tidx) + row_in_tile = g2s_thr_copy_lse.partition_S( + cute.make_identity_tensor((self.tile_m, self.topk)) + )[0, 0, 0][0] + if tile_begin + row_in_tile < total_flat: + gLSE_tile = cute.local_tile(mLSE_partial_tma, (self.tile_m, self.topk), (m_block, 0)) + cute.copy( + g2s_tiled_copy_lse, + g2s_thr_copy_lse.partition_S(gLSE_tile), + g2s_thr_copy_lse.partition_D(sLSE_tma[None, None, 0]), + ) + cute.arch.cp_async_mbarrier_arrive_noinc(lse_mbar) + primed_stages = const_expr(min(self.stages, self.topk)) + # One warp puts the LSE tile and the first ring slots in flight; they land while the + # CTA decodes its rows. if warp_idx == 0: - for stage in cutlass.range(self.stages, unroll_full=True): - o_tma_barrier = sO_tma_mbar_ptr + stage + if const_expr(self.lse_split_aligned): with cute.arch.elect_one(): - cute.arch.mbarrier_arrive_and_expect_tx( - o_tma_barrier, - o_tma_copy_bytes, - ) + cute.arch.mbarrier_arrive_and_expect_tx(lse_mbar, lse_tma_bytes) + cute.copy( + tma_atom_LSE, + tLSEgLSE_tma[None, m_block], + tLSEsLSE_tma[None, 0], + tma_bar_ptr=lse_mbar, + ) + for stage in cutlass.range(primed_stages, unroll_full=True): + with cute.arch.elect_one(): + cute.arch.mbarrier_arrive_and_expect_tx(ring_mbar + stage, o_tma_bytes) cute.copy( tma_atom_O_partial, - tOgO_tma[ - None, - m_block + Int32(stage) * row_tiles_per_split, - ], + tOgO_tma[None, m_block, Int32(stage)], tOsO_tma[None, stage], - tma_bar_ptr=o_tma_barrier, + tma_bar_ptr=ring_mbar + stage, ) - # Four adjacent lanes own one row and four interleaved split pairs. - reduce_lane = tidx % Int32(4) - reduce_row = tidx // Int32(4) - reduce_flat = tile_begin + reduce_row - row_valid = reduce_flat < total_flat - m_idx = Int32(0) - head_idx = Int32(0) - row_split_count = Int32(0) - if row_valid: - m_idx, head_idx = self.decode_flat_row_idx( - reduce_flat, - head_divmod, - ) - row_split_count = ( - mSplitCounts[m_idx, head_idx // qhead_per_kvhead] - if const_expr(mSplitCounts is not None) - else Int32(self.topk) - ) - - local_page_max = cute.make_rmem_tensor((4,), Float32) - local_page_sum = cute.make_rmem_tensor((4,), Float32) - raw_stats = cute.make_rmem_tensor((2,), Float32) - local_max = -Float32.inf - local_max_valid = Int32(-1) - for item in cutlass.range(4, unroll_full=True): - split = reduce_lane + item * Int32(4) - raw_stats[0] = -Float32.inf - raw_stats[1] = Float32(0.0) - if row_valid and split < row_split_count: - cute.copy( - raw_stats_copy_atom, - mRawStats[m_idx, split, head_idx, None], - raw_stats, - ) - stats_valid = ( - raw_stats[1] > Float32(0.0) - and raw_stats[1] < Float32.inf - and raw_stats[0] > -Float32.inf - and raw_stats[0] < Float32.inf - and raw_stats[0] == raw_stats[0] - and raw_stats[1] == raw_stats[1] - ) - page_max = raw_stats[0] if stats_valid else -Float32.inf - page_sum = raw_stats[1] if stats_valid else Float32(0.0) - local_page_max[item] = page_max - local_page_sum[item] = page_sum - local_max = max(local_max, page_max) - if stats_valid: - local_max_valid = split + cO = cute.make_identity_tensor((self.tile_m, self.head_dim)) + thr_copy_partial = tiled_copy_partial.get_slice(tidx) + tOcO = thr_copy_partial.partition_D(cO) + tOsO = thr_copy_partial.partition_D(sO) + num_rows = const_expr(cute.size(tOcO, mode=[1])) - stats_max = cute.arch.warp_reduction_max( - local_max, - threads_in_group=4, - ) - max_valid_split = cute.arch.warp_reduction_max( - local_max_valid, - threads_in_group=4, - ) - stats_max_safe = ( - stats_max if max_valid_split >= Int32(0) else Float32(0.0) - ) - stats_sum = Float32(0.0) - for item in cutlass.range(4, unroll_full=True): - split_scale = cute.math.exp2( - local_page_max[item] - stats_max_safe, - fastmath=True, - ) - local_page_max[item] = split_scale - stats_sum += split_scale * local_page_sum[item] - stats_sum = cute.arch.warp_reduction_sum( - stats_sum, - threads_in_group=4, - ) - stats_sum_valid = ( - max_valid_split >= Int32(0) - and stats_sum > Float32(0.0) - and stats_sum < Float32.inf - and stats_sum == stats_sum - ) - inv_sum = Float32(0.0) - final_lse = -Float32.inf - if stats_sum_valid: - inv_sum = Float32(1.0) / stats_sum - final_lse = ( - stats_max + cute.math.log2(stats_sum, fastmath=True) - ) * Float32(math.log(2.0)) - for item in cutlass.range(4, unroll_full=True): - split = reduce_lane + item * Int32(4) - sLSE[split, reduce_row] = local_page_max[item] * inv_sum - if reduce_lane == Int32(0): - sMaxValidSplit[reduce_row] = max_valid_split - if const_expr(mLSE is not None): - if row_valid: - mLSE[m_idx, head_idx] = final_lse + # The LSE tile holds stale values past a row's valid split count and past the last row: + # fetch each row's count before the wait and mask after the transpose. + cLSE = cute.make_identity_tensor((self.topk, self.tile_m)) + s2r_thr_copy_lse = s2r_tiled_copy_lse.get_slice(tidx) + ts2rsLSE = s2r_thr_copy_lse.partition_S(sLSE) + ts2rcLSE = s2r_thr_copy_lse.partition_S(cLSE) + ts2rrLSE = cute.make_rmem_tensor_like(ts2rsLSE) + lse_rows = const_expr(cute.size(ts2rrLSE, mode=[2])) + lse_splits = const_expr(cute.size(ts2rrLSE, mode=[1])) + lse_row_count = cute.make_rmem_tensor(lse_rows, Int32) + for m in cutlass.range(lse_rows, unroll_full=True): + row_idx = tile_begin + ts2rcLSE[0, 0, m][1] + lse_row_count[m] = Int32(0) + if row_idx < total_flat: + if const_expr(mSplitCounts is not None): + row_q, row_h = divmod(row_idx, head_divmod) + lse_row_count[m] = mSplitCounts[row_q, row_h // qhead_per_kvhead] + else: + lse_row_count[m] = Int32(self.topk) + cute.arch.mbarrier_wait(lse_mbar, 0) + cute.copy(s2r_tiled_copy_lse, ts2rsLSE, ts2rrLSE) + for m in cutlass.range(lse_rows, unroll_full=True): + for sp in cutlass.range(lse_splits, unroll_full=True): + if ts2rcLSE[0, sp, 0][0] >= lse_row_count[m]: + ts2rrLSE[0, sp, m] = -Float32.inf + + # Per row: the max LSE over the valid splits, the split weights exp(lse - max) normalized + # by their sum (written back over the LSE tile), the final LSE, and the last valid split. + final_lse = cute.make_rmem_tensor(lse_rows, Float32) + max_valid_split = cute.make_rmem_tensor(lse_rows, Int32) + threads_per_row = const_expr(self.lse_threads_per_row) + LOG2_E = math.log2(math.e) + for m in cutlass.range(lse_rows, unroll_full=True): + lse_max = cute.arch.warp_reduction_max( + ts2rrLSE[None, None, m] + .load() + .reduce(cute.ReductionOp.MAX, init_val=-Float32.inf, reduction_profile=0), + threads_in_group=threads_per_row, + ) + max_valid_idx = -1 + for sp in cutlass.range(lse_splits, unroll_full=True): + if ts2rrLSE[0, sp, m] != -Float32.inf: + max_valid_idx = ts2rcLSE[0, sp, 0][0] + max_valid_split[m] = cute.arch.warp_reduction_max( + max_valid_idx, threads_in_group=threads_per_row + ) + # A row without valid splits has max -inf; its weights are exp2(-inf) = 0. + lse_max_cur = 0.0 if lse_max == -Float32.inf else lse_max + lse_sum_cur = 0.0 + for sp in cutlass.range(lse_splits, unroll_full=True): + scale = cute.math.exp2( + ts2rrLSE[0, sp, m] * LOG2_E - (lse_max_cur * LOG2_E), fastmath=True + ) + lse_sum_cur += scale + ts2rrLSE[0, sp, m] = scale + lse_sum_cur = cute.arch.warp_reduction_sum( + lse_sum_cur, threads_in_group=threads_per_row + ) + inv_sum = 0.0 + if max_valid_split[m] < 0 or lse_sum_cur == 0.0 or lse_sum_cur != lse_sum_cur: + final_lse[m] = -Float32.inf + else: + final_lse[m] = cute.math.log(lse_sum_cur, fastmath=True) + lse_max + inv_sum = 1.0 / lse_sum_cur + ts2rrLSE[None, None, m].store(ts2rrLSE[None, None, m].load() * inv_sum) + cute.copy(s2r_tiled_copy_lse, ts2rrLSE, ts2rsLSE) + + # The ring is shared by the CTA, so the split loop runs to the tile's deepest valid + # split: one slot per warp, reduced after the barrier below. + thread_max_valid_split = max_valid_split[0] + for m in cutlass.range(1, lse_rows, unroll_full=True): + thread_max_valid_split = max(thread_max_valid_split, max_valid_split[m]) + warp_max_valid_split = cute.arch.warp_reduction_max( + thread_max_valid_split, threads_in_group=32 + ) + if tidx % 32 == 0: + sBlockMaxValidSplit[tidx // 32] = warp_max_valid_split + + if const_expr(mLSE is not None): + for m in cutlass.range(lse_rows, unroll_full=True): + if ts2rcLSE[0, 0, m][0] == 0: # the lane holding split 0 writes the row + row_idx = tile_begin + ts2rcLSE[0, 0, m][1] + if row_idx < total_flat: + row_q, row_h = divmod(row_idx, head_divmod) + mLSE[row_q, row_h] = final_lse[m] cute.arch.sync_threads() - block_max_valid_split = Int32(-1) - if const_expr(self.tile_m == 32): - if tidx < Int32(self.tile_m): - block_max_valid_split = cute.arch.warp_reduction_max( - sMaxValidSplit[tidx], - threads_in_group=self.tile_m, - ) - if tidx == 0: - sMaxValidSplit[0] = block_max_valid_split - else: - if tidx < Int32(32): - block_max_valid_split = cute.arch.warp_reduction_max( - max( - sMaxValidSplit[tidx], - sMaxValidSplit[tidx + Int32(32)], - ), - threads_in_group=32, - ) - if tidx == 0: - sMaxValidSplit[0] = block_max_valid_split - cute.arch.sync_threads() - block_max_valid_split = sMaxValidSplit[0] - - cO = cute.make_identity_tensor((self.tile_m, self.k_block_size)) - partial_copy = gmem_tiled_copy_O_partial.get_slice(tidx) - tOcO = partial_copy.partition_D(cO) - tOsO_partial = partial_copy.partition_D(sO) - num_rows = const_expr(cute.size(tOcO, mode=[1])) - tOrO_partial_row = cute.make_rmem_tensor_like( - tOsO_partial[None, 0, None, 0] - ) - tOrO = cute.make_rmem_tensor_like( - tOsO_partial[None, None, None, 0], - Float32, - ) + block_max_valid_split = sBlockMaxValidSplit[0] + for wi in cutlass.range(1, self.num_warps, unroll_full=True): + block_max_valid_split = max(block_max_valid_split, sBlockMaxValidSplit[wi]) + + # Accumulate the weighted partials in FP32. A row's weight is zero for its invalid splits + # and for every split of a row past the last one, so stale partial rows never reach the + # sum. + tOrO_partial = cute.make_rmem_tensor_like(tOsO[None, None, None, 0]) + tOrO = cute.make_rmem_tensor_like(tOrO_partial, Float32) tOrO.fill(0.0) - - for split in cutlass.range(block_max_valid_split + 1, unroll=4): - stage = split % Int32(self.stages) - phase = (split // Int32(self.stages)) & Int32(1) - cute.arch.mbarrier_wait(sO_tma_mbar_ptr + stage, phase) - for row in cutlass.range(num_rows, unroll_full=True): - cute.autovec_copy( - tOsO_partial[None, row, None, stage], - tOrO_partial_row, - ) - weight = sLSE[split, tOcO[0, row, 0][0]] - if weight != Float32(0.0): - tOrO[None, row, None].store( - tOrO[None, row, None].load() - + weight - * tOrO_partial_row.load().to(Float32) + for s in cutlass.range(block_max_valid_split + 1, unroll=2): + stage = s % Int32(self.stages) + phase = (s // Int32(self.stages)) & Int32(1) + scale = cute.make_rmem_tensor(num_rows, Float32) + for m in cutlass.range(num_rows, unroll_full=True): + scale[m] = sLSE[s, tOcO[0, m, 0][0]] + cute.arch.mbarrier_wait(ring_mbar + stage, phase) + cute.autovec_copy(tOsO[None, None, None, stage], tOrO_partial) + for m in cutlass.range(num_rows, unroll_full=True): + if scale[m] > 0.0: + tOrO[None, m, None].store( + tOrO[None, m, None].load() + + scale[m] * tOrO_partial[None, m, None].load().to(Float32) ) - + # Every thread has copied this slot to registers before it is refilled. cute.arch.sync_threads() - split_to_load = split + Int32(self.stages) + split_to_load = s + Int32(self.stages) if warp_idx == 0 and split_to_load <= block_max_valid_split: - o_tma_barrier = sO_tma_mbar_ptr + stage with cute.arch.elect_one(): - cute.arch.mbarrier_arrive_and_expect_tx( - o_tma_barrier, - o_tma_copy_bytes, - ) + cute.arch.mbarrier_arrive_and_expect_tx(ring_mbar + stage, o_tma_bytes) cute.copy( tma_atom_O_partial, - tOgO_tma[ - None, - m_block + split_to_load * row_tiles_per_split, - ], + tOgO_tma[None, m_block, split_to_load], tOsO_tma[None, stage], - tma_bar_ptr=o_tma_barrier, - ) - - # Transpose the four 32-bit BF16 pairs within each four-lane group, - # then retain one coalesced 128-bit output store per row. - output_copy = gmem_tiled_copy_O.get_slice(tidx) - tOcO_store = output_copy.partition_D(cO) - rO_row = cute.make_rmem_tensor( - tOcO_store[None, 0, 0].shape, - self.dtype, - ) - elems_per_store = const_expr( - cute.size(gmem_tiled_copy_O.layout_tv_tiled[1]) - ) - num_store_rows = const_expr(cute.size(tOcO_store, mode=[1])) + tma_bar_ptr=ring_mbar + stage, + ) + + # Primed slots the split loop did not consume still have a bulk copy in flight; wait for + # them so none lands after the CTA has exited. + for stage in cutlass.range(primed_stages, unroll_full=True): + if Int32(stage) > block_max_valid_split: + cute.arch.mbarrier_wait(ring_mbar + stage, 0) + + # The partial columns are a 4x4 transpose of 32-bit pairs inside each 32-column group: + # undo it with two XOR-shuffle stages across the four lanes that share the group, then + # keep the coalesced 128-bit store. No shared memory, no barrier. + thr_copy_out = tiled_copy_out.get_slice(tidx) + tOcO_store = thr_copy_out.partition_D(cO) + rO = cute.make_rmem_tensor(tOcO_store.shape, self.dtype) + elems_per_store = const_expr(cute.size(tiled_copy_out.layout_tv_tiled[1])) + num_vals = const_expr(cute.size(tOcO, mode=[0])) + assert num_vals == 8 and cute.size(tOcO_store, mode=[1]) == num_rows lane_in_pair_group = tidx % Int32(4) - for row in cutlass.range(num_store_rows, unroll_full=True): - for k in cutlass.range( - cute.size(tOcO_store, mode=[2]), - unroll_full=True, - ): - o0, o1 = tOrO[0, row, k], tOrO[1, row, k] - o2, o3 = tOrO[2, row, k], tOrO[3, row, k] - o4, o5 = tOrO[4, row, k], tOrO[5, row, k] - o6, o7 = tOrO[6, row, k], tOrO[7, row, k] - if const_expr(mOutputScale is not None): - o0, o1 = cute.arch.mul_packed_f32x2( - (o0, o1), - (output_scale, output_scale), - ) - o2, o3 = cute.arch.mul_packed_f32x2( - (o2, o3), - (output_scale, output_scale), - ) - o4, o5 = cute.arch.mul_packed_f32x2( - (o4, o5), - (output_scale, output_scale), - ) - o6, o7 = cute.arch.mul_packed_f32x2( - (o6, o7), - (output_scale, output_scale), - ) - word0 = utils.cvt_f16x2_f32(o0, o1, self.dtype) - word1 = utils.cvt_f16x2_f32(o2, o3, self.dtype) - word2 = utils.cvt_f16x2_f32(o4, o5, self.dtype) - word3 = utils.cvt_f16x2_f32(o6, o7, self.dtype) + for m in cutlass.range(num_rows, unroll_full=True): + for k in cutlass.range(cute.size(tOcO_store, mode=[2]), unroll_full=True): + word0 = utils.cvt_f16x2_f32(tOrO[0, m, k], tOrO[1, m, k], self.dtype) + word1 = utils.cvt_f16x2_f32(tOrO[2, m, k], tOrO[3, m, k], self.dtype) + word2 = utils.cvt_f16x2_f32(tOrO[4, m, k], tOrO[5, m, k], self.dtype) + word3 = utils.cvt_f16x2_f32(tOrO[6, m, k], tOrO[7, m, k], self.dtype) partner0 = cute.arch.shuffle_sync_bfly(word1, offset=1) partner1 = cute.arch.shuffle_sync_bfly(word0, offset=1) @@ -933,1054 +656,61 @@ def kernel_tma_raw( if lane_in_pair_group // Int32(2) != Int32(1): out2, out3 = partner2, partner3 - rO_pairs = cute.recast_tensor(rO_row, cutlass.Int32) + rO_pairs = cute.recast_tensor(rO[None, m, k], Int32) rO_pairs[0] = out0 rO_pairs[1] = out1 rO_pairs[2] = out2 rO_pairs[3] = out3 - row_local = tOcO_store[0, row, 0][0] - flat_idx = tile_begin + row_local - if flat_idx < total_flat: - m_idx, head_idx = self.decode_flat_row_idx( - flat_idx, - head_divmod, - ) - mO_cur_copy = cute.tiled_divide( - mO[m_idx, None, head_idx], - (elems_per_store,), - ) - k_idx = tOcO_store[0, 0, k][1] // elems_per_store - cute.copy( - output_copy, - rO_row, - mO_cur_copy[None, k_idx], - ) - - @cute.kernel - def kernel( - self, - mO_partial: cute.Tensor, - mO_partial_tma: Optional[cute.Tensor], - mLSE_partial: cute.Tensor, - mRowSum_partial: Optional[cute.Tensor], - mRawStats: Optional[cute.Tensor], - mO: cute.Tensor, - mLSE: Optional[cute.Tensor], - mLSE_temperature_partial: Optional[cute.Tensor], - mLSE_temperature: Optional[cute.Tensor], - cu_seqlens: Optional[cute.Tensor], - seqused: Optional[cute.Tensor], - num_splits_dynamic_ptr: Optional[cute.Tensor], - varlen_batch_idx: Optional[cute.Tensor], - semaphore_to_reset: Optional[cute.Tensor], - mSplitCounts: Optional[cute.Tensor], - mOutputScale: Optional[cute.Tensor], - qhead_per_kvhead: Int32, - tma_atom_O_partial: Optional[cute.CopyAtom], - raw_stats_copy_atom: Optional[cute.CopyAtom], - SharedStorage: cutlass.Constexpr, - smem_layout_lse: cute.Layout | cute.ComposedLayout, - smem_layout_lse_aux: cute.Layout | cute.ComposedLayout, - smem_layout_o: cute.Layout | cute.ComposedLayout, - smem_layout_o_tma: Optional[cute.Layout], - smem_layout_perm: cute.Layout, - gmem_tiled_copy_O_partial: cute.TiledCopy, - gmem_tiled_copy_O: cute.TiledCopy, - gmem_tiled_copy_LSE: cute.TiledCopy, - s2r_tiled_copy_LSE: cute.TiledCopy, - seqlen_divmod: FastDivmodDivisor, - head_divmod: FastDivmodDivisor, - use_pdl: cutlass.Constexpr[bool], - varlen: cutlass.Constexpr[bool], - flatten_varlen: cutlass.Constexpr[bool], - ): - # Thread and block indices - tidx, _, _ = cute.arch.thread_idx() - warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) - m_block, k_block, maybe_virtual_batch = cute.arch.block_idx() - - if const_expr(flatten_varlen): - batch_idx = Int32(0) - else: - batch_idx = ( - varlen_batch_idx[maybe_virtual_batch] - if const_expr(varlen_batch_idx is not None) - else maybe_virtual_batch - ) - - # /////////////////////////////////////////////////////////////////////////////// - # Get shared memory buffer - # /////////////////////////////////////////////////////////////////////////////// - smem = cutlass.utils.SmemAllocator() - storage = smem.allocate(SharedStorage) - sLSE = storage.sLSE.get_tensor(smem_layout_lse) - sLSE_temperature = storage.sLSETemperature.get_tensor(smem_layout_lse_aux) - sMaxValidSplit = storage.sMaxValidSplit.get_tensor((self.tile_m,)) - sO = storage.sO.get_tensor(smem_layout_o) - sO_tma = None - sO_tma_mbar_ptr = None - if const_expr(self.use_tma_partial): - sO_tma = storage.sO.get_tensor(smem_layout_o_tma) - sO_tma_mbar_ptr = storage.sOTmaMbar.data_ptr() - sO_perm_buf = storage.sO_perm.get_tensor(smem_layout_perm) - - # Handle semaphore reset — wait for dependent grids first - if const_expr(use_pdl and semaphore_to_reset is not None): - if ( - tidx == 0 - and m_block == cute.arch.grid_dim()[0] - 1 - and k_block == cute.arch.grid_dim()[1] - 1 - and maybe_virtual_batch == cute.arch.grid_dim()[2] - 1 - ): - cute.arch.griddepcontrol_wait() - semaphore_to_reset[0] = 0 - if const_expr(num_splits_dynamic_ptr is not None): - raise ValueError("K2 combine requires compile-time exact topK") - num_splits = Int32(self.topk) - # Concatenated varlen tensors already have total_q as their leading - # extent. Other modes retain SeqlenInfo-based per-batch slicing. - if const_expr(flatten_varlen): - seqlen = Int32(mO_partial.shape[0]) - offset = Int32(0) - else: - seqlen_info = SeqlenInfo.create( - batch_idx=batch_idx, - seqlen_static=mO_partial.shape[0], - cu_seqlens=cu_seqlens, - seqused=seqused, - # Don't need tile size because offset_padded is unused. - ) - seqlen, offset = seqlen_info.seqlen, seqlen_info.offset - - num_head = mO_partial.shape[3] - max_idx = seqlen * num_head - output_scale = Float32(1.0) - if const_expr(mOutputScale is not None): - output_scale = mOutputScale[0] - - if const_expr(not varlen) or m_block * self.tile_m < max_idx: - # Wait for dependent grids (e.g., the main attention kernel that produces O_partial/LSE_partial) - if const_expr(use_pdl): - cute.arch.griddepcontrol_wait() - - # =============================== - # Step 1: Load LSE_partial from gmem to shared memory - # =============================== - # `cLSE` (identity tensor for row/split coord tracking) is reused - # later in steps 4-5, so it must be defined on both branches. - cLSE = cute.make_identity_tensor((self.topk, self.tile_m)) - # Reshape mLSE_partial to PackGQA packed layout and delegate the - # tile load to PackGQAComb.load_LSE. The packed form folds (H_q, Sq) - # into one compound dim with H_q innermost (stride 1), so thread - # rows that vary along h_pos produce one-sector coalesced reads. - # Non-varlen path only — varlen keeps the original inline loop. - if const_expr(not varlen): - mLSE_partial_cur = seqlen_info.offset_batch(mLSE_partial, batch_idx, dim=3) - # mLSE_partial_cur: (H_q, topK, Sq) — after initial transpose - # [3,0,2,1] on [topK,B,Sq,H_q] and dropping B. - # Reorder to (H_q, Sq, topK) then group modes 0..1 for packed dim: - mLSE_partial_reord = cute.make_tensor( - mLSE_partial_cur.iterator, - cute.select(mLSE_partial_cur.layout, mode=[0, 2, 1]), - ) - mLSE_partial_packed = cute.group_modes(mLSE_partial_reord, 0, 2) - # shape ((H_q, Sq), topK) with H_q innermost. - packgqa = PackGQAComb( - m_block_size=self.tile_m, - head_dim_padded=0, # unused for LSE load - check_hdim_oob=False, # unused for LSE load - qhead_per_kvhead=1, # unused; num_heads_divmod is passed explicitly - ) - packgqa.load_LSE( - mLSE_partial_packed, - sLSE, - self.topk, - gmem_tiled_copy_LSE, - tidx, - m_block, - num_splits, - seqlen, - head_divmod, - mSplitCounts, - batch_idx, - qhead_per_kvhead, - ) - if const_expr(mLSE_temperature_partial is not None): - mLSE_temperature_partial_cur = seqlen_info.offset_batch( - mLSE_temperature_partial, batch_idx, dim=3) - mLSE_temperature_partial_reord = cute.make_tensor( - mLSE_temperature_partial_cur.iterator, - cute.select(mLSE_temperature_partial_cur.layout, mode=[0, 2, 1]), - ) - mLSE_temperature_partial_packed = cute.group_modes( - mLSE_temperature_partial_reord, 0, 2) - packgqa.load_LSE( - mLSE_temperature_partial_packed, - sLSE_temperature, - self.topk, - gmem_tiled_copy_LSE, - tidx, - m_block, - num_splits, - seqlen, - head_divmod, - mSplitCounts, - batch_idx, - qhead_per_kvhead, - ) - else: - # Varlen path keeps the same H_q-innermost flat-row contract: - # after transpose [1, 0, 2], mLSE_partial_cur is - # (q_local, split, head). - # mSplitCounts is the authoritative valid-split count per - # packed (q_abs, kv_head); masked splits stay at -inf and - # therefore drop out of the final kernel LSE_out reduction. - if const_expr(flatten_varlen): - mLSE_partial_cur = mLSE_partial - if const_expr(self.raw_partial_stats): - mRowSum_partial_cur = mRowSum_partial - else: - mLSE_partial_cur = seqlen_info.offset_batch( - mLSE_partial, batch_idx, dim=3 - ) - if const_expr(self.raw_partial_stats): - mRowSum_partial_cur = seqlen_info.offset_batch( - mRowSum_partial, batch_idx, dim=3 - ) - mLSE_partial_copy = cute.tiled_divide(mLSE_partial_cur, (1,)) - if const_expr(self.raw_partial_stats): - mRowSum_partial_copy = cute.tiled_divide(mRowSum_partial_cur, (1,)) - gmem_thr_copy_LSE = gmem_tiled_copy_LSE.get_slice(tidx) - tLSEsLSE = gmem_thr_copy_LSE.partition_D(sLSE) - tLSEsLSE_temperature = gmem_thr_copy_LSE.partition_D(sLSE_temperature) - tLSEcLSE = gmem_thr_copy_LSE.partition_S(cLSE) - if const_expr(mLSE_temperature_partial is not None): - if const_expr(flatten_varlen): - mLSE_temperature_partial_cur = mLSE_temperature_partial - else: - mLSE_temperature_partial_cur = seqlen_info.offset_batch( - mLSE_temperature_partial, batch_idx, dim=3 - ) - mLSE_temperature_partial_copy = cute.tiled_divide( - mLSE_temperature_partial_cur, (1,)) - - for m in cutlass.range(cute.size(tLSEcLSE, mode=[2]), unroll_full=True): - mi = tLSEcLSE[0, 0, m][1] - idx = m_block * self.tile_m + mi - if idx < max_idx: - m_idx, head_idx = self.decode_flat_row_idx(idx, head_divmod) - row_count = ( - mSplitCounts[offset + m_idx, head_idx // qhead_per_kvhead] - if const_expr(mSplitCounts is not None) - else num_splits - ) - mLSE_partial_cur_copy = mLSE_partial_copy[None, m_idx, None, head_idx] - if const_expr(self.raw_partial_stats): - mRowSum_partial_cur_copy = ( - mRowSum_partial_copy[None, m_idx, None, head_idx] - ) - if const_expr(mLSE_temperature_partial is not None): - mLSE_temperature_partial_cur_copy = ( - mLSE_temperature_partial_copy[None, m_idx, None, head_idx]) - for s in cutlass.range(cute.size(tLSEcLSE, mode=[1]), unroll_full=True): - si = tLSEcLSE[0, s, 0][0] - if si < num_splits and si < row_count: - cute.copy( - gmem_thr_copy_LSE, - mLSE_partial_cur_copy[None, si], - tLSEsLSE[None, s, m], - ) - if const_expr(self.raw_partial_stats): - cute.copy( - gmem_thr_copy_LSE, - mRowSum_partial_cur_copy[None, si], - tLSEsLSE_temperature[None, s, m], - ) - if const_expr(mLSE_temperature_partial is not None): - cute.copy( - gmem_thr_copy_LSE, - mLSE_temperature_partial_cur_copy[None, si], - tLSEsLSE_temperature[None, s, m], - ) - else: - tLSEsLSE[None, s, m].fill(-Float32.inf) - if const_expr(self.raw_partial_stats): - tLSEsLSE_temperature[None, s, m].fill(Float32(0.0)) - if const_expr(mLSE_temperature_partial is not None): - tLSEsLSE_temperature[None, s, m].fill(-Float32.inf) - else: - for s in cutlass.range(cute.size(tLSEcLSE, mode=[1]), unroll_full=True): - tLSEsLSE[None, s, m].fill(-Float32.inf) - if const_expr(self.raw_partial_stats): - tLSEsLSE_temperature[None, s, m].fill(Float32(0.0)) - if const_expr(mLSE_temperature_partial is not None): - tLSEsLSE_temperature[None, s, m].fill(-Float32.inf) - cute.arch.cp_async_commit_group() - - # =============================== - # Step 2: Load O_partial for pipeline stages - # =============================== - - gmem_thr_copy_O_partial = gmem_tiled_copy_O_partial.get_slice(tidx) - cO = cute.make_identity_tensor((self.tile_m, self.k_block_size)) - tOcO = gmem_thr_copy_O_partial.partition_D(cO) - tOsO_partial = gmem_thr_copy_O_partial.partition_D(sO) - - # Precompute per-row values for flattened (q_local, head) tiles. - num_rows = const_expr(cute.size(tOcO, mode=[1])) - tOmidx = cute.make_rmem_tensor(num_rows, cutlass.Int32) - tOhidx = cute.make_rmem_tensor(num_rows, cutlass.Int32) - if const_expr(not self.use_tma_partial): - tOSplitCount = cute.make_rmem_tensor(num_rows, cutlass.Int32) - tOrOptr = cute.make_rmem_tensor(num_rows, cutlass.Int64) - if const_expr(flatten_varlen): - mO_partial_cur = mO_partial - else: - mO_partial_cur = seqlen_info.offset_batch( - mO_partial, batch_idx, dim=4 - ) - for m in cutlass.range(num_rows, unroll_full=True): - mi = tOcO[0, m, 0][0] # m coordinate in tile - idx = m_block * self.tile_m + mi - if idx >= max_idx: - tOhidx[m] = -1 - tOmidx[m] = 0 - if const_expr(not self.use_tma_partial): - tOSplitCount[m] = 0 - tOrOptr[m] = cutlass.Int64(0) - else: - tOmidx[m], tOhidx[m] = self.decode_flat_row_idx(idx, head_divmod) - if const_expr(not self.use_tma_partial): - if const_expr(mSplitCounts is None): - tOSplitCount[m] = num_splits - elif const_expr(cu_seqlens is None): - tOSplitCount[m] = mSplitCounts[ - batch_idx, tOmidx[m], tOhidx[m] // qhead_per_kvhead - ] - else: - tOSplitCount[m] = mSplitCounts[ - offset + tOmidx[m], tOhidx[m] // qhead_per_kvhead - ] - tOrOptr[m] = utils.elem_pointer( - mO_partial_cur, - (tOmidx[m], k_block * self.k_block_size, 0, tOhidx[m]), - ).toint() - - tOpO = None - if const_expr(not self.is_even_k): - tOpO = cute.make_rmem_tensor(cute.size(tOcO, mode=[2]), Boolean) - for k in cutlass.range(cute.size(tOpO), unroll_full=True): - tOpO[k] = tOcO[0, 0, k][1] < mO_partial.shape[1] - k_block * self.k_block_size - if const_expr(self.use_tma_partial): - gO_partial_tma = cute.local_tile( - mO_partial_tma, - (self.k_block_size, self.tile_m), - (k_block, m_block, None), - ) - tOsO_tma, tOgO_tma = cpasync.tma_partition( - tma_atom_O_partial, - 0, - cute.make_layout(1), - cute.group_modes(sO_tma, 0, 2), - cute.group_modes(gO_partial_tma, 0, 2), - ) - o_tma_copy_bytes = const_expr( - cute.size_in_bytes( - self.dtype_partial, - cute.select(smem_layout_o_tma, mode=[0, 1]), - ) - ) - if tidx == 0: - for stage in cutlass.range(self.stages, unroll_full=True): - cute.arch.mbarrier_init(sO_tma_mbar_ptr + stage, 1) - cute.arch.mbarrier_init_fence() - cute.arch.sync_threads() - if warp_idx == 0: - for stage in cutlass.range(self.stages, unroll_full=True): - o_tma_barrier = sO_tma_mbar_ptr + stage - with cute.arch.elect_one(): - cute.arch.mbarrier_arrive_and_expect_tx( - o_tma_barrier, - o_tma_copy_bytes, - ) - cute.copy( - tma_atom_O_partial, - tOgO_tma[None, stage], - tOsO_tma[None, stage], - tma_bar_ptr=o_tma_barrier, - ) - else: - load_O_partial = partial( - self.load_O_partial, - gmem_tiled_copy_O_partial, - tOrOptr, - tOsO_partial, - tOhidx, - tOSplitCount, - tOpO, - tOcO, - mO_partial_cur.layout, - ) - - # Load the initial cp.async stages of O_partial. - for stage in cutlass.range(self.stages - 1, unroll_full=True): - if stage < num_splits: - load_O_partial(stage, stage) - cute.arch.cp_async_commit_group() - - # =============================== - # Step 3: Load and transpose LSE from smem to registers - # =============================== - - # Wait for LSE and initial O partial stages to complete - if const_expr(self.use_tma_partial): - cute.arch.cp_async_wait_group(0) - else: - cute.arch.cp_async_wait_group(self.stages - 1) - cute.arch.sync_threads() - - s2r_thr_copy_LSE = s2r_tiled_copy_LSE.get_slice(tidx) - ts2rsLSE = s2r_thr_copy_LSE.partition_S(sLSE) - ts2rrLSE = cute.make_rmem_tensor_like(ts2rsLSE) - cute.copy(s2r_tiled_copy_LSE, ts2rsLSE, ts2rrLSE) - if const_expr( - self.raw_partial_stats or mLSE_temperature_partial is not None - ): - ts2rsLSE_temperature = s2r_thr_copy_LSE.partition_S(sLSE_temperature) - ts2rrLSE_temperature = cute.make_rmem_tensor_like(ts2rsLSE_temperature) - cute.copy( - s2r_tiled_copy_LSE, - ts2rsLSE_temperature, - ts2rrLSE_temperature, - ) - - # =============================== - # Step 4: Compute final LSE along split dimension - # =============================== - - final_lse = cute.make_rmem_tensor(cute.size(ts2rrLSE, mode=[2]), Float32) - ts2rcLSE = s2r_thr_copy_LSE.partition_D(cLSE) - # We compute the max valid split for each row to short-circuit the computation later - max_valid_split = cute.make_rmem_tensor(cute.size(ts2rrLSE, mode=[2]), Int32) - assert cute.size(ts2rrLSE, mode=[0]) == 1 - # Compute max, scales, and final LSE for each row. Invalid splits - # have already been filled with -inf, so Step 5 can write the - # kernel-native LSE_out directly. - for m in cutlass.range(cute.size(ts2rrLSE, mode=[2]), unroll_full=True): - threads_per_col = const_expr(self.smem_threads_per_col_lse) - if const_expr(self.raw_partial_stats): - # Sanitize the raw pair before reductions so NaN/Inf cannot - # contaminate a neighboring split in the thread group. - max_valid_idx = Int32(-1) - for s in cutlass.range( - cute.size(ts2rrLSE, mode=[1]), unroll_full=True - ): - scaled_max_log2 = ts2rrLSE[0, s, m] - row_sum = ts2rrLSE_temperature[0, s, m] - stats_valid = ( - row_sum > Float32(0.0) - and row_sum < Float32.inf - and scaled_max_log2 > -Float32.inf - and scaled_max_log2 < Float32.inf - and row_sum == row_sum - and scaled_max_log2 == scaled_max_log2 - ) - ts2rrLSE[0, s, m] = ( - scaled_max_log2 if stats_valid else -Float32.inf - ) - ts2rrLSE_temperature[0, s, m] = ( - row_sum if stats_valid else Float32(0.0) - ) - if stats_valid: - max_valid_idx = ts2rcLSE[0, s, 0][0] - - stats_max = cute.arch.warp_reduction_max( - ts2rrLSE[None, None, m] - .load() - .reduce( - cute.ReductionOp.MAX, - init_val=-Float32.inf, - reduction_profile=0, - ), - threads_in_group=threads_per_col, - ) - max_valid_split[m] = cute.arch.warp_reduction_max( - max_valid_idx, threads_in_group=threads_per_col - ) - stats_max_safe = ( - stats_max - if max_valid_split[m] >= Int32(0) - else Float32(0.0) - ) - stats_sum = Float32(0.0) - for s in cutlass.range( - cute.size(ts2rrLSE, mode=[1]), unroll_full=True - ): - row_sum = ts2rrLSE_temperature[0, s, m] - split_scale = Float32(0.0) - if row_sum > Float32(0.0): - split_scale = cute.math.exp2( - ts2rrLSE[0, s, m] - stats_max_safe, - fastmath=True, - ) - stats_sum += split_scale * row_sum - # Raw partial-O already includes the local row sum, so - # its combine weight excludes row_sum from the numerator. - ts2rrLSE[0, s, m] = split_scale - stats_sum = cute.arch.warp_reduction_sum( - stats_sum, threads_in_group=threads_per_col - ) - stats_sum_valid = ( - max_valid_split[m] >= Int32(0) - and stats_sum > Float32(0.0) - and stats_sum < Float32.inf - and stats_sum == stats_sum - ) - inv_sum = Float32(0.0) - if stats_sum_valid: - inv_sum = Float32(1.0) / stats_sum - final_lse[m] = ( - stats_max - + cute.math.log2(stats_sum, fastmath=True) - ) * Float32(math.log(2.0)) - else: - final_lse[m] = -Float32.inf - ts2rrLSE[None, None, m].store( - ts2rrLSE[None, None, m].load() * inv_sum - ) - else: - # Find max normalized-partial LSE value across splits. - lse_max = cute.arch.warp_reduction_max( - ts2rrLSE[None, None, m] - .load() - .reduce( - cute.ReductionOp.MAX, - init_val=-Float32.inf, - reduction_profile=0, - ), - threads_in_group=threads_per_col, - ) - max_valid_idx = -1 - for s in cutlass.range( - cute.size(ts2rrLSE, mode=[1]), unroll_full=True - ): - if ts2rrLSE[0, s, m] != -Float32.inf: - max_valid_idx = ts2rcLSE[0, s, 0][0] - max_valid_split[m] = cute.arch.warp_reduction_max( - max_valid_idx, threads_in_group=threads_per_col - ) - lse_max_cur = Float32(0.0) if lse_max == -Float32.inf else lse_max - LOG2_E = math.log2(math.e) - lse_sum_cur = Float32(0.0) - for s in cutlass.range( - cute.size(ts2rrLSE, mode=[1]), unroll_full=True - ): - scale = cute.math.exp2( - ts2rrLSE[0, s, m] * LOG2_E - - lse_max_cur * LOG2_E, - fastmath=True, - ) - lse_sum_cur += scale - ts2rrLSE[0, s, m] = scale - lse_sum_cur = cute.arch.warp_reduction_sum( - lse_sum_cur, threads_in_group=threads_per_col - ) - inv_sum = Float32(0.0) - if ( - max_valid_split[m] < 0 - or lse_sum_cur == Float32(0.0) - or lse_sum_cur != lse_sum_cur - ): - final_lse[m] = -Float32.inf - else: - final_lse[m] = ( - cute.math.log(lse_sum_cur, fastmath=True) + lse_max - ) - inv_sum = Float32(1.0) / lse_sum_cur - ts2rrLSE[None, None, m].store( - ts2rrLSE[None, None, m].load() * inv_sum - ) - # Store the scales exp(lse - lse_logsum) back to smem - cute.copy(s2r_tiled_copy_LSE, ts2rrLSE, ts2rsLSE) - - if const_expr(mLSE_temperature_partial is not None): - final_lse_temperature = cute.make_rmem_tensor( - cute.size(ts2rrLSE_temperature, mode=[2]), Float32) - for m in cutlass.range(cute.size(ts2rrLSE_temperature, mode=[2]), unroll_full=True): - threads_per_col = const_expr(self.smem_threads_per_col_lse) - lse_temperature_max = cute.arch.warp_reduction_max( - ts2rrLSE_temperature[None, None, m] - .load() - .reduce( - cute.ReductionOp.MAX, - init_val=-Float32.inf, - reduction_profile=0, - ), - threads_in_group=threads_per_col, - ) - lse_temperature_max_cur = ( - 0.0 if lse_temperature_max == -Float32.inf else lse_temperature_max - ) - LOG2_E = math.log2(math.e) - lse_temperature_sum_cur = 0.0 - for s in cutlass.range( - cute.size(ts2rrLSE_temperature, mode=[1]), unroll_full=True): - scale = cute.math.exp2( - ts2rrLSE_temperature[0, s, m] * LOG2_E - - (lse_temperature_max_cur * LOG2_E), - fastmath=True, - ) - lse_temperature_sum_cur += scale - lse_temperature_sum_cur = cute.arch.warp_reduction_sum( - lse_temperature_sum_cur, threads_in_group=threads_per_col - ) - if ( - max_valid_split[m] < 0 - or lse_temperature_sum_cur == 0.0 - or lse_temperature_sum_cur != lse_temperature_sum_cur - ): - final_lse_temperature[m] = -Float32.inf - else: - final_lse_temperature[m] = ( - cute.math.log(lse_temperature_sum_cur, fastmath=True) - + lse_temperature_max - ) - - # Store max valid split to smem - for m in cutlass.range(cute.size(ts2rrLSE, mode=[2]), unroll_full=True): - if ts2rcLSE[0, 0, m][0] == 0: # Only thread responsible for s=0 writes - mi = ts2rcLSE[0, 0, m][1] - if mi < self.tile_m: - sMaxValidSplit[mi] = max_valid_split[m] - - # =============================== - # Step 5: Store final LSE to gmem - # This writeback is the authoritative LSE_out returned by the - # public Sparse Attention / Sparse Page Attention interface. - # =============================== - - if const_expr(mLSE is not None): - if const_expr(cu_seqlens is None): - mLSE_cur = mLSE[None, None, batch_idx] - else: - mLSE_cur = cute.domain_offset((offset, 0), mLSE) - if const_expr(mLSE_temperature is not None): - if const_expr(cu_seqlens is None): - mLSE_temperature_cur = mLSE_temperature[None, None, batch_idx] - else: - mLSE_temperature_cur = cute.domain_offset( - (offset, 0), mLSE_temperature) - if k_block == 0: # Only first k_block writes LSE when mLSE is provided - for m in cutlass.range(cute.size(ts2rrLSE, mode=[2]), unroll_full=True): - if ts2rcLSE[0, 0, m][0] == 0: # Only thread responsible for s=0 writes - mi = ts2rcLSE[0, 0, m][1] - idx = m_block * self.tile_m + mi - if idx < max_idx: - m_idx, head_idx = self.decode_flat_row_idx(idx, head_divmod) - mLSE_cur[m_idx, head_idx] = final_lse[m] - if const_expr(mLSE_temperature is not None): - mLSE_temperature_cur[m_idx, head_idx] = ( - final_lse_temperature[m]) - - # =============================== - # Step 6: Read O_partial and accumulate final O - # =============================== - - cute.arch.sync_threads() - - if const_expr(self.use_tma_partial): - # TMA stages are CTA-wide resources, so every consumer thread - # must execute the same split count and barrier sequence. - block_max_valid_split = Int32(-1) - if tidx < Int32(self.tile_m): - block_max_valid_split = cute.arch.warp_reduction_max( - sMaxValidSplit[tidx], threads_in_group=self.tile_m - ) - if tidx == 0: - sMaxValidSplit[0] = block_max_valid_split - cute.arch.sync_threads() - thr_max_valid_split = sMaxValidSplit[0] - else: - # cp.async loads are thread-private, so each thread can stop at - # the largest valid split among its own rows. - thr_max_valid_split = sMaxValidSplit[tOcO[0, 0, 0][0]] - for m in cutlass.range( - 1, cute.size(tOcO, mode=[1]), unroll_full=True - ): - thr_max_valid_split = max( - thr_max_valid_split, - sMaxValidSplit[tOcO[0, m, 0][0]], - ) - - tOrO_partial = cute.make_rmem_tensor_like(tOsO_partial[None, None, None, 0]) - tOrO = cute.make_rmem_tensor_like(tOrO_partial, Float32) - tOrO.fill(0.0) - - stage_load = Int32(self.stages - 1) - stage_compute = Int32(0) - - # Main accumulation loop - for s in cutlass.range(thr_max_valid_split + 1, unroll=4): - if const_expr(self.use_tma_partial): - stage_compute = s % Int32(self.stages) - stage_phase = (s // Int32(self.stages)) & Int32(1) - cute.arch.mbarrier_wait( - sO_tma_mbar_ptr + stage_compute, - stage_phase, - ) - - # Get scales for this split - scale = cute.make_rmem_tensor(num_rows, Float32) - for m in cutlass.range(num_rows, unroll_full=True): - scale[m] = sLSE[s, tOcO[0, m, 0][0]] - - if const_expr(self.use_tma_partial): - cute.autovec_copy( - tOsO_partial[None, None, None, stage_compute], - tOrO_partial, - ) - else: - # Load the next thread-private cp.async stage. - split_to_load = s + self.stages - 1 - if split_to_load <= thr_max_valid_split: - load_O_partial(split_to_load, stage_load) - cute.arch.cp_async_commit_group() - stage_load = ( - 0 if stage_load == self.stages - 1 else stage_load + 1 - ) - cute.arch.cp_async_wait_group(self.stages - 1) - cute.autovec_copy( - tOsO_partial[None, None, None, stage_compute], - tOrO_partial, - ) - stage_compute = ( - 0 - if stage_compute == self.stages - 1 - else stage_compute + 1 - ) - - # Accumulate scaled partial results - for m in cutlass.range(num_rows, unroll_full=True): - if tOhidx[m] >= 0 and scale[m] > 0.0: - tOrO[None, m, None].store( - tOrO[None, m, None].load() - + scale[m] * tOrO_partial[None, m, None].load().to(Float32) - ) - - if const_expr(self.use_tma_partial): - # Match CUDA's CTA-wide stage handoff: no consumer may - # release a stage while another warp is still reading it. - cute.arch.sync_threads() - split_to_load = s + self.stages - if warp_idx == 0 and split_to_load <= thr_max_valid_split: - o_tma_barrier = sO_tma_mbar_ptr + stage_compute - with cute.arch.elect_one(): - cute.arch.mbarrier_arrive_and_expect_tx( - o_tma_barrier, - o_tma_copy_bytes, - ) - cute.copy( - tma_atom_O_partial, - tOgO_tma[None, split_to_load], - tOsO_tma[None, stage_compute], - tma_bar_ptr=o_tma_barrier, - ) - - # Flush any outstanding async-copy groups before the local Step-7 - # permutation buffer is read on the tail of the kernel. - if const_expr(not self.use_tma_partial): - cute.arch.cp_async_wait_group(0) - cute.arch.sync_threads() - - # =============================== - # Step 7: Write final O to gmem (fake→real via SMEM) - # =============================== - - if const_expr(cu_seqlens is None): - mO_cur = mO[None, None, None, batch_idx] - elif const_expr(flatten_varlen): - mO_cur = mO - else: - mO_cur = cute.domain_offset((offset, 0, 0), mO) - mO_cur = utils.domain_offset_aligned((0, k_block * self.k_block_size, 0), mO_cur) - num_vals = const_expr(cute.size(tOcO, mode=[0])) - if const_expr(not use_pdl): - # Direct / standalone calls don't participate in the K1->K2 - # dependency chain. Use a simple per-element real-column store - # path here to keep mixed-shape launches stable. - for m in cutlass.range(num_rows, unroll_full=True): - if tOhidx[m] >= 0: - for k in cutlass.range(cute.size(tOcO, mode=[2]), unroll_full=True): - if const_expr(self.is_even_k) or tOpO[k]: - for v in cutlass.range(num_vals, unroll_full=True): - fake_col = tOcO[v, 0, k][1] - real_col = stg128_half_fake_col_to_real_col(fake_col) - o_val = tOrO[v, m, k] - if const_expr(mOutputScale is not None): - o_val = o_val * output_scale - mO_cur[tOmidx[m], real_col, tOhidx[m]] = o_val.to(self.dtype) - elif const_expr(self.dtype in [cutlass.BFloat16, cutlass.Float16]): - # The BF16/F16 fake layout is a 4x4 transpose of 32-bit - # pairs inside each 32-column group. Transpose the pair - # registers with two XOR-shuffle stages, then retain the - # original coalesced 128-bit GMEM store. - assert num_vals == 8 - gmem_thr_copy_O = gmem_tiled_copy_O.get_slice(tidx) - tOcO_store = gmem_thr_copy_O.partition_D(cO) - rO = cute.make_rmem_tensor(tOcO_store.shape, self.dtype) - elems_per_store = const_expr( - cute.size(gmem_tiled_copy_O.layout_tv_tiled[1]) - ) - num_store_rows = const_expr(cute.size(tOcO_store, mode=[1])) - assert num_store_rows == num_rows - lane_in_pair_group = tidx % Int32(4) - - for m in cutlass.range(num_store_rows, unroll_full=True): - for k in cutlass.range( - cute.size(tOcO_store, mode=[2]), unroll_full=True - ): - o0, o1 = tOrO[0, m, k], tOrO[1, m, k] - o2, o3 = tOrO[2, m, k], tOrO[3, m, k] - o4, o5 = tOrO[4, m, k], tOrO[5, m, k] - o6, o7 = tOrO[6, m, k], tOrO[7, m, k] - if const_expr(mOutputScale is not None): - o0, o1 = cute.arch.mul_packed_f32x2( - (o0, o1), (output_scale, output_scale) - ) - o2, o3 = cute.arch.mul_packed_f32x2( - (o2, o3), (output_scale, output_scale) - ) - o4, o5 = cute.arch.mul_packed_f32x2( - (o4, o5), (output_scale, output_scale) - ) - o6, o7 = cute.arch.mul_packed_f32x2( - (o6, o7), (output_scale, output_scale) - ) - word0 = utils.cvt_f16x2_f32(o0, o1, self.dtype) - word1 = utils.cvt_f16x2_f32(o2, o3, self.dtype) - word2 = utils.cvt_f16x2_f32(o4, o5, self.dtype) - word3 = utils.cvt_f16x2_f32(o6, o7, self.dtype) - - partner0 = cute.arch.shuffle_sync_bfly(word1, offset=1) - partner1 = cute.arch.shuffle_sync_bfly(word0, offset=1) - partner2 = cute.arch.shuffle_sync_bfly(word3, offset=1) - partner3 = cute.arch.shuffle_sync_bfly(word2, offset=1) - stage0, stage1 = word0, word1 - stage2, stage3 = word2, word3 - if lane_in_pair_group % Int32(2) != Int32(0): - stage0, stage2 = partner0, partner2 - if lane_in_pair_group % Int32(2) != Int32(1): - stage1, stage3 = partner1, partner3 - - partner0 = cute.arch.shuffle_sync_bfly(stage2, offset=2) - partner1 = cute.arch.shuffle_sync_bfly(stage3, offset=2) - partner2 = cute.arch.shuffle_sync_bfly(stage0, offset=2) - partner3 = cute.arch.shuffle_sync_bfly(stage1, offset=2) - out0, out1 = stage0, stage1 - out2, out3 = stage2, stage3 - if lane_in_pair_group // Int32(2) != Int32(0): - out0, out1 = partner0, partner1 - if lane_in_pair_group // Int32(2) != Int32(1): - out2, out3 = partner2, partner3 - - rO_pairs = cute.recast_tensor( - rO[None, m, k], cutlass.Int32 - ) - rO_pairs[0] = out0 - rO_pairs[1] = out1 - rO_pairs[2] = out2 - rO_pairs[3] = out3 - - for m in cutlass.range(num_store_rows, unroll_full=True): - row_local = tOcO_store[0, m, 0][0] - idx = m_block * self.tile_m + row_local - if idx < max_idx: - m_idx, head_idx = self.decode_flat_row_idx( - idx, head_divmod - ) - mO_cur_copy = cute.tiled_divide( - mO_cur[m_idx, None, head_idx], (elems_per_store,) - ) - for k in cutlass.range( - cute.size(tOcO_store, mode=[2]), unroll_full=True - ): - k_idx = ( - tOcO_store[0, 0, k][1] // elems_per_store - ) - cute.copy( - gmem_thr_copy_O, - rO[None, m, k], - mO_cur_copy[None, k_idx], - ) - else: - # 7a: fp32 accumulator -> output dtype SMEM with fake→real - # permutation. The dedicated permutation buffer stays separate - # from the O_partial pipeline staging buffer. - sO_perm = sO_perm_buf - - if const_expr(self.dtype in [cutlass.BFloat16, cutlass.Float16]): - # O_partial uses a dtype-specific STG.128 fake layout, but - # sO_perm is in the final O dtype. For all supported fake - # layouts, adjacent fake pairs map to adjacent real columns, - # so write the final BF16/F16 O pair as one 32-bit SMEM store. - assert num_vals % 2 == 0 - r2s_o_pair_atom = cute.make_copy_atom( - cute.nvgpu.CopyUniversalOp(), - cutlass.Int32, - num_bits_per_copy=32, - ) - rO_pair_word = cute.make_rmem_tensor((1,), cutlass.Int32) - sO_perm_i32_base = cute.make_ptr( - dtype=cutlass.Int32, - value=sO_perm.iterator.toint(), - mem_space=sO_perm.iterator.memspace, - assumed_align=4, - ) - sO_perm_i32_row_stride = Int32((self.k_block_size + 16) // 2) - for m in cutlass.range(num_rows, unroll_full=True): - row_local = tOcO[0, m, 0][0] - if tOhidx[m] >= 0: - for k in cutlass.range(cute.size(tOcO, mode=[2]), unroll_full=True): - for v_pair in cutlass.range(num_vals // 2, unroll_full=True): - v = v_pair * 2 - fake_col = tOcO[v, 0, k][1] - real_col = stg128_half_fake_col_to_real_col(fake_col) - o0 = tOrO[v, m, k] - o1 = tOrO[v + 1, m, k] - if const_expr(mOutputScale is not None): - o0, o1 = cute.arch.mul_packed_f32x2( - (o0, o1), - (output_scale, output_scale), - ) - rO_pair_word[0] = utils.cvt_f16x2_f32(o0, o1, self.dtype) - smem_pair_ptr = cute.make_ptr( - dtype=cutlass.Int32, - value=( - sO_perm_i32_base.toint() - + Int64( - row_local * sO_perm_i32_row_stride - + real_col // Int32(2) - ) - * Int64(4) - ), - mem_space=sO_perm.iterator.memspace, - assumed_align=4, - ) - sO_pair = cute.make_tensor( - smem_pair_ptr, - cute.make_layout((1,), stride=(1,)), - ) - cute.copy(r2s_o_pair_atom, rO_pair_word, sO_pair) - else: - # 7a: iterate over ALL val elements in mode[0]. - # tOcO[v, m, k][1] gives different fake_col for each v. - r2s_o_scalar_atom = cute.make_copy_atom( - cute.nvgpu.CopyUniversalOp(), - self.dtype, - num_bits_per_copy=self.dtype.width, - ) - rO_scalar = cute.make_rmem_tensor((1,), self.dtype) - for m in cutlass.range(num_rows, unroll_full=True): - row_local = tOcO[0, m, 0][0] - if tOhidx[m] >= 0: - for k in cutlass.range(cute.size(tOcO, mode=[2]), unroll_full=True): - for v in cutlass.range(num_vals, unroll_full=True): - fake_col = tOcO[v, 0, k][1] - real_col = stg128_half_fake_col_to_real_col(fake_col) - o_val = tOrO[v, m, k] - if const_expr(mOutputScale is not None): - o_val = o_val * output_scale - rO_scalar[0] = o_val.to(self.dtype) - smem_ptr = utils.elem_pointer(sO_perm, (row_local, real_col)) - smem_scalar_ptr = cute.make_ptr( - dtype=self.dtype, - value=smem_ptr.toint(), - mem_space=sO_perm.iterator.memspace, - assumed_align=self.dtype.width // 8, - ) - sO_scalar = cute.make_tensor( - smem_scalar_ptr, - cute.make_layout((1,), stride=(1,)), - ) - cute.copy(r2s_o_scalar_atom, rO_scalar, sO_scalar) - - cute.arch.sync_threads() - - # 7b: SMEM (real order, output dtype) → GMEM - gmem_thr_copy_O = gmem_tiled_copy_O.get_slice(tidx) - tOcO_store = gmem_thr_copy_O.partition_D(cO) - tOsO_store = gmem_thr_copy_O.partition_D(sO_perm) - rO = cute.make_rmem_tensor(tOcO_store.shape, self.dtype) - elems_per_store = const_expr(cute.size(gmem_tiled_copy_O.layout_tv_tiled[1])) - num_store_rows = const_expr(cute.size(tOcO_store, mode=[1])) - tOpO_store = None - if const_expr(not self.is_even_k): - tOpO_store = cute.make_rmem_tensor(cute.size(tOcO_store, mode=[2]), Boolean) - for k in cutlass.range(cute.size(tOpO_store), unroll_full=True): - tOpO_store[k] = ( - tOcO_store[0, 0, k][1] - < mO_partial.shape[1] - k_block * self.k_block_size - ) - - # Read output dtype from SMEM (now in real column order). - for m in cutlass.range(num_store_rows, unroll_full=True): - for k in cutlass.range(cute.size(tOcO_store, mode=[2]), unroll_full=True): - if const_expr(self.is_even_k) or tOpO_store[k]: - cute.autovec_copy(tOsO_store[None, m, k], rO[None, m, k]) - - # Write bf16 to GMEM using gmem_tiled_copy_O (same as original FA Step 7) - for m in cutlass.range(num_store_rows, unroll_full=True): - row_local = tOcO_store[0, m, 0][0] - idx = m_block * self.tile_m + row_local - if idx < max_idx: - m_idx, head_idx = self.decode_flat_row_idx(idx, head_divmod) - mO_cur_copy = cute.tiled_divide( - mO_cur[m_idx, None, head_idx], (elems_per_store,) - ) - for k in cutlass.range(cute.size(tOcO_store, mode=[2]), unroll_full=True): - k_idx = tOcO_store[0, 0, k][1] // elems_per_store - if const_expr(self.is_even_k) or tOpO_store[k]: - cute.copy(gmem_thr_copy_O, rO[None, m, k], mO_cur_copy[None, k_idx]) + for m in cutlass.range(num_rows, unroll_full=True): + idx = tile_begin + tOcO_store[0, m, 0][0] + if idx < total_flat: + row_q, row_h = divmod(idx, head_divmod) + mO_row = cute.tiled_divide(mO[row_q, row_h, None], (elems_per_store,)) + for k in cutlass.range(cute.size(tOcO_store, mode=[2]), unroll_full=True): + k_idx = tOcO_store[0, 0, k][1] // elems_per_store + cute.copy(thr_copy_out, rO[None, m, k], mO_row[None, k_idx]) @cute.jit - def load_O_partial( + def claim_tile( self, - gmem_tiled_copy_O_partial: cute.TiledCopy, - tOrOptr: cute.Tensor, - tOsO_partial: cute.Tensor, - tOhidx: cute.Tensor, - tOSplitCount: cute.Tensor, - tOpO: Optional[cute.Tensor], - tOcO: cute.Tensor, - mO_cur_partial_layout: cute.Layout, - split: Int32, - stage: Int32, - ) -> None: - elems_per_load = const_expr(cute.size(gmem_tiled_copy_O_partial.layout_tv_tiled[1])) - tOsO_partial_cur = tOsO_partial[None, None, None, stage] - for m in cutlass.range(cute.size(tOcO, [1]), unroll_full=True): - if tOhidx[m] >= 0: - o_gmem_ptr = cute.make_ptr( - tOsO_partial.element_type, - tOrOptr[m], - cute.AddressSpace.gmem, - assumed_align=16, - ) - mO_partial_cur = cute.make_tensor( - o_gmem_ptr, cute.slice_(mO_cur_partial_layout, (0, None, None, 0)) - ) - mO_partial_cur_copy = cute.tiled_divide(mO_partial_cur, (elems_per_load,)) - for k in cutlass.range(cute.size(tOcO, mode=[2]), unroll_full=True): - k_idx = tOcO[0, 0, k][1] // elems_per_load - if split < tOSplitCount[m] and (const_expr(tOpO is None) or tOpO[k]): - cute.copy( - gmem_tiled_copy_O_partial, - mO_partial_cur_copy[None, k_idx, split], - tOsO_partial_cur[None, m, k], - ) - else: - tOsO_partial_cur[None, m, k].fill(0) + mSmDomains: cute.Tensor, + mTileCounters: cute.Tensor, + total_tiles: Int32, + tiles_per_page_log2: Int32, + ) -> Int32: + """One tile for this CTA, from the domain of its SM while that domain has tiles left. + + Tiles are dealt to domains by page: page ``j`` (``2 ** tiles_per_page_log2`` tiles) + belongs to domain ``j % num_domains``, so the ``k``-th tile of domain ``d`` is tile + ``k % page`` of page ``(k // page) * num_domains + d``. Each counter hands out claims in + order; a claim past the domain's tile count moves on to the next domain, and since the + grid holds exactly one CTA per tile, the claims of all domains together always fit. + """ + num_domains = const_expr(self.num_domains) + sm_id = cute.arch.smid() + domain = mSmDomains[sm_id] + if domain < 0: + domain = sm_id % Int32(num_domains) + page_tiles = Int32(1) << tiles_per_page_log2 + full_pages = total_tiles >> tiles_per_page_log2 + tail_tiles = total_tiles & (page_tiles - 1) + tile = Int32(-1) + for _ in cutlass.range_constexpr(num_domains): + if tile < 0: + claim = cute.arch.atomic_add(mTileCounters.iterator + domain, Int32(1)) + domain_pages = full_pages // Int32(num_domains) + if full_pages % Int32(num_domains) > domain: + domain_pages = domain_pages + 1 + domain_tiles = domain_pages << tiles_per_page_log2 + if full_pages % Int32(num_domains) == domain: + domain_tiles = domain_tiles + tail_tiles + if claim < domain_tiles: + page = (claim >> tiles_per_page_log2) * Int32(num_domains) + domain + tile = (page << tiles_per_page_log2) + (claim & (page_tiles - 1)) + else: + domain = (domain + 1) % Int32(num_domains) + return tile def _get_cutlass_dtype(torch_dtype: torch.dtype): @@ -1989,34 +719,17 @@ def _get_cutlass_dtype(torch_dtype: torch.dtype): return torch2cute_dtype_map[torch_dtype] -_combine_compile_cache = {} +def _check_cuda_aligned(tensor: torch.Tensor, *, name: str, device: torch.device) -> None: + if tensor.device != device: + raise ValueError(f"{name} must be on {device}, got {tensor.device}") + if tensor.data_ptr() % 16: + raise ValueError(f"{name} must be 16-byte aligned") -def _get_cpasync_smem_layout_atom(dtype: Type[cutlass.Numeric], k_dim: int) -> cute.ComposedLayout: - dtype_byte = const_expr(dtype.width // 8) - bytes_per_row = const_expr(k_dim * dtype_byte) - smem_k_block_size = ( - const_expr( - 128 - if bytes_per_row % 128 == 0 - else (64 if bytes_per_row % 64 == 0 else (32 if bytes_per_row % 32 == 0 else 16)) - ) - // dtype_byte - ) - swizzle_bits = ( - 4 - if smem_k_block_size == 128 - else (3 if smem_k_block_size == 64 else (2 if smem_k_block_size == 32 else 1)) - ) - swizzle_base = 2 if dtype_byte == 4 else (3 if dtype_byte == 2 else 4) - return cute.make_composed_layout( - cute.make_swizzle(swizzle_bits, swizzle_base, swizzle_base), - 0, - cute.make_ordered_layout( - (8 if const_expr(k_dim % 32 == 0) else 16, smem_k_block_size), - order=(1, 0), - ), - ) +def _check_cuda_contiguous(tensor: torch.Tensor, *, name: str, device: torch.device) -> None: + _check_cuda_aligned(tensor, name=name, device=device) + if not tensor.is_contiguous(): + raise ValueError(f"{name} must be contiguous") def combine( @@ -2025,315 +738,210 @@ def combine( o_out, lse_out, *, - lse_temperature_partial=None, - lse_temperature_out=None, - cu_seqlens=None, - seqused=None, split_counts=None, - output_scale=None, use_pdl=False, - raw_partial_stats=False, + locality=None, ): - """K2: merge sparse forward split partials into the final output. + """K2: merge the sparse forward's split partials into the final output. - STG.128 fake-layout handling remains an internal implementation detail. - When lse_out is provided, the kernel writes the final authoritative - log-sum-exp for each query row/head directly into that tensor. + Every (query, head) row is combined on its own, so the tensors use the varlen (``total_q``) + layout whatever the batch structure. When ``lse_out`` is given, the kernel writes the final + log-sum-exp of each row into it. Args: - o_partial_fake: - Batched: [num_splits, batch, Sq, head_q, dim] - Varlen: [num_splits, total_q, head_q, dim] - lse_partial: - Batched: [num_splits, batch, Sq, head_q] - Varlen: [num_splits, total_q, head_q] - o_out: - Batched: [batch, Sq, head_q, dim] - Varlen: [total_q, head_q, dim] - lse_out: - Batched: [batch, Sq, head_q] - Varlen: [total_q, head_q] - lse_temperature_partial: - Optional temperature-scaled LSE partial with the same shape as - lse_partial. - lse_temperature_out: - Optional temperature-scaled final LSE with the same shape as - lse_out. - cu_seqlens: Optional [batch + 1] int32 for varlen-Q combine. - seqused: Optional [batch] int32 effective lengths for combine. - split_counts: Optional int32 rowwise valid split counts prepared from - q2k metadata. Batched: [batch, seqlen, head_kv]. Varlen: - [total_q, head_kv]. - output_scale: Optional fp32 tensor with at least one element. When - provided, the final O accumulator is multiplied once before store. - use_pdl: When True, wait on PDL dependencies from the producer K1 - kernel. When False, launch without PDL waits. - raw_partial_stats: Interpret lse_partial as interleaved FP32 - (scaled_max_log2, row_sum) pairs and combine raw partial-O. + o_partial_fake: [num_splits, total_q, head_q, 128] BF16 or F16, columns in the forward + epilogue's STG.128 order; the rows of a split slab are contiguous, the slabs may be + padded apart (any 16-byte-aligned split stride). + lse_partial: [num_splits, total_q, head_q] FP32, contiguous. + o_out: [total_q, head_q, 128] BF16 or F16, contiguous. + lse_out: [total_q, head_q] FP32, or None. + split_counts: optional [total_q, head_kv] int32 valid split count per row; splits at or + past a row's count are ignored. ``head_q`` must be a multiple of ``head_kv``. + use_pdl: wait on the producer grid (programmatic dependent launch) before reading. + locality: optional :class:`LocalityHints` for a partial buffer striped over the memory + locality domains; every CTA then reads its tile from the domain of its own SM. """ - D = o_partial_fake.shape[-1] - num_splits = o_partial_fake.shape[0] - raw_partial_stats = bool(raw_partial_stats) - return_temperature_lse = ( - lse_temperature_partial is not None or lse_temperature_out is not None - ) - if (lse_temperature_partial is None) != (lse_temperature_out is None): + if o_partial_fake.ndim != 4: + raise ValueError( + f"o_partial_fake must be [num_splits, total_q, head_q, dim], got {tuple(o_partial_fake.shape)}" + ) + num_splits, total_q, head_q, dim = o_partial_fake.shape + if dim != 128: + raise ValueError(f"the combine supports head dim 128, got {dim}") + if not 1 <= num_splits <= 256: + raise ValueError(f"num_splits must be in [1, 256], got {num_splits}") + split_stride = o_partial_fake.stride(0) + if o_partial_fake.stride()[1:] != (head_q * dim, dim, 1) or split_stride < total_q * head_q * dim: raise ValueError( - "lse_temperature_partial and lse_temperature_out must either both be provided or both be None" + "o_partial_fake rows must be contiguous inside each split slab, with a split stride " + f"of at least {total_q * head_q * dim} elements, got strides {o_partial_fake.stride()}" + ) + if split_stride % (128 // (8 * o_partial_fake.element_size())): + raise ValueError("the o_partial_fake split stride must keep 16-byte alignment") + if split_stride >= MAX_SPLIT_SLAB_ELEMENTS: + raise ValueError(f"the o_partial_fake split stride must be below {MAX_SPLIT_SLAB_ELEMENTS}") + if o_partial_fake.dtype not in (torch.bfloat16, torch.float16): + raise TypeError( + f"o_partial_fake dtype must be torch.bfloat16 or torch.float16, got {o_partial_fake.dtype}" + ) + if o_out.dtype not in (torch.bfloat16, torch.float16): + raise TypeError(f"o_out dtype must be torch.bfloat16 or torch.float16, got {o_out.dtype}") + if tuple(o_out.shape) != (total_q, head_q, dim): + raise ValueError( + f"o_out must have shape {(total_q, head_q, dim)}, got {tuple(o_out.shape)}" ) - if raw_partial_stats: - expected_stats_shape = (*o_partial_fake.shape[:-1], 2) - if tuple(lse_partial.shape) != tuple(expected_stats_shape): - raise ValueError( - "raw lse_partial must have shape " - f"{expected_stats_shape}, got {tuple(lse_partial.shape)}" - ) - if cu_seqlens is None or o_partial_fake.ndim != 4: - raise ValueError("raw_partial_stats currently requires varlen partial tensors") - if return_temperature_lse: - raise ValueError("raw_partial_stats does not support independent temperature LSE") - else: - expected_lse_shape = o_partial_fake.shape[:-1] - if tuple(lse_partial.shape) != tuple(expected_lse_shape): - raise ValueError( - "lse_partial shape must match o_partial_fake without head_dim, " - f"got {tuple(lse_partial.shape)} vs {tuple(expected_lse_shape)}" - ) if lse_partial.dtype != torch.float32: raise TypeError(f"lse_partial must be torch.float32, got {lse_partial.dtype}") - if lse_temperature_partial is not None and lse_temperature_partial.shape != lse_partial.shape: + if tuple(lse_partial.shape) != (num_splits, total_q, head_q): raise ValueError( - "lse_temperature_partial must have the same shape as lse_partial, " - f"got {lse_temperature_partial.shape} vs {lse_partial.shape}" + f"lse_partial must have shape {(num_splits, total_q, head_q)}, got {tuple(lse_partial.shape)}" ) - if lse_temperature_out is not None: - if lse_out is None: - raise ValueError("lse_temperature_out requires lse_out") - if lse_temperature_out.shape != lse_out.shape: + if lse_out is not None: + if lse_out.dtype != torch.float32: + raise TypeError(f"lse_out must be torch.float32, got {lse_out.dtype}") + if tuple(lse_out.shape) != (total_q, head_q): raise ValueError( - "lse_temperature_out must have the same shape as lse_out, " - f"got {lse_temperature_out.shape} vs {lse_out.shape}" + f"lse_out must have shape {(total_q, head_q)}, got {tuple(lse_out.shape)}" ) - if lse_temperature_out.dtype != torch.float32 or lse_temperature_partial.dtype != torch.float32: - raise TypeError("temperature LSE tensors must be torch.float32") - - if o_partial_fake.dtype not in (torch.bfloat16, torch.float16): - raise TypeError( - "o_partial_fake dtype must be torch.bfloat16 or torch.float16, " - f"got {o_partial_fake.dtype}" - ) - partial_dtype = _get_cutlass_dtype(o_partial_fake.dtype) - out_dtype = _get_cutlass_dtype(o_out.dtype) - if output_scale is not None: - if output_scale.dtype != torch.float32: - raise TypeError(f"output_scale must be torch.float32, got {output_scale.dtype}") - if output_scale.numel() < 1: - raise ValueError("output_scale must contain at least one element") - if output_scale.device != o_out.device: - raise ValueError("output_scale must be on the same device as o_out") - output_scale = output_scale.contiguous() if split_counts is not None: if split_counts.dtype != torch.int32: raise TypeError(f"split_counts must be torch.int32, got {split_counts.dtype}") - if o_out.ndim == 4: - if split_counts.ndim != 3: - raise ValueError( - f"batched split_counts must have shape [batch, seqlen, head_kv], got {split_counts.shape}" - ) - if split_counts.shape[:2] != o_out.shape[:2]: - raise ValueError( - f"split_counts shape {split_counts.shape} must match batch/seqlen of o_out {o_out.shape}" - ) - else: - if cu_seqlens is None: - raise ValueError("split_counts with varlen output requires cu_seqlens") - if split_counts.ndim != 2: - raise ValueError( - f"varlen split_counts must have shape [total_q, head_kv], got {split_counts.shape}" - ) - if split_counts.shape[0] != o_out.shape[0]: - raise ValueError( - f"split_counts total_q ({split_counts.shape[0]}) must match o_out total_q " - f"({o_out.shape[0]})" - ) - if o_out.shape[-2] % split_counts.shape[-1] != 0: + if split_counts.ndim != 2 or split_counts.shape[0] != total_q: raise ValueError( - f"o_out heads ({o_out.shape[-2]}) must be divisible by split_counts heads ({split_counts.shape[-1]})" + f"split_counts must have shape [total_q, head_kv], got {tuple(split_counts.shape)}" ) - qheadperkv = o_out.shape[-2] // split_counts.shape[-1] - else: - qheadperkv = 1 - if cu_seqlens is not None: - if cu_seqlens.dtype != torch.int32: - raise TypeError(f"cu_seqlens must be torch.int32, got {cu_seqlens.dtype}") - if cu_seqlens.ndim != 1: - raise ValueError(f"cu_seqlens must be rank-1, got {cu_seqlens.shape}") - if not cu_seqlens.is_contiguous(): - raise ValueError("cu_seqlens must be contiguous") - if seqused is not None: - if seqused.dtype != torch.int32: - raise TypeError(f"seqused must be torch.int32, got {seqused.dtype}") - if seqused.ndim != 1: - raise ValueError(f"seqused must be rank-1, got {seqused.shape}") - if not seqused.is_contiguous(): - raise ValueError("seqused must be contiguous") + if head_q % split_counts.shape[1] != 0: + raise ValueError( + f"head_q ({head_q}) must be divisible by split_counts heads ({split_counts.shape[1]})" + ) + device = o_out.device + if not o_out.is_cuda: + raise ValueError("o_out must be a CUDA tensor") + _check_cuda_aligned(o_partial_fake, name="o_partial_fake", device=device) + for name, tensor in ( + ("lse_partial", lse_partial), + ("o_out", o_out), + ("lse_out", lse_out), + ("split_counts", split_counts), + ): + if tensor is not None: + _check_cuda_contiguous(tensor, name=name, device=device) - k_block_size = 128 if D > 64 else 64 - tile_m = 64 if raw_partial_stats else 32 - num_threads = tile_m * 4 - has_cu_seqlens = cu_seqlens is not None - has_seqused = seqused is not None + partial_dtype = _get_cutlass_dtype(o_partial_fake.dtype) + out_dtype = _get_cutlass_dtype(o_out.dtype) has_lse = lse_out is not None has_split_counts = split_counts is not None - has_output_scale = output_scale is not None - min_blocks_per_mp = 3 if has_output_scale and use_pdl else 0 + qhead_per_kvhead = head_q // split_counts.shape[1] if has_split_counts else 1 + num_domains = 0 + tiles_per_page_log2 = 0 + if locality is not None: + num_domains = locality.num_domains + if num_domains < 2: + raise ValueError("locality hints need at least two domains") + for name, tensor in ( + ("locality.sm_domains", locality.sm_domains), + ("locality.tile_counters", locality.tile_counters), + ): + _check_cuda_contiguous(tensor, name=name, device=device) + if tensor.dtype != torch.int32 or tensor.ndim != 1: + raise TypeError(f"{name} must be a one-dimensional torch.int32 tensor") + tile_bytes = TILE_M * dim * o_partial_fake.element_size() + tiles_per_page, page_rest = divmod(locality.page_bytes, tile_bytes) + if page_rest or tiles_per_page & (tiles_per_page - 1): + raise ValueError( + f"locality.page_bytes must be a power-of-two multiple of the {tile_bytes}-byte tile" + ) + tiles_per_page_log2 = tiles_per_page.bit_length() - 1 + if (split_stride * o_partial_fake.element_size()) % (num_domains * locality.page_bytes): + raise ValueError( + "the o_partial_fake split stride must be a multiple of num_domains x page_bytes " + "so the pages of every slab fall into the same domains" + ) + # A tensor map's split stride must be 16-byte aligned: with a head count that is a multiple + # of 4 every split's FP32 LSE slab is, whatever total_q, and one 2-D box loads a tile's LSEs; + # otherwise the kernel brings the tile in with 4-byte cp.async copies. + lse_split_aligned = head_q % 4 == 0 + capability = torch.cuda.get_device_capability(device) + # Unsteered reads on SM107 are fabric-bound; see STAGES_INTERLEAVED. + stages = STAGES_INTERLEAVED if capability == (10, 7) and not num_domains else STAGES - capability = torch.cuda.get_device_capability(o_out.device) - stages = 4 if capability == (10, 7) else 2 key = ( "combine", capability, + dim, + TILE_M, + NUM_THREADS, stages, - D, - k_block_size, - tile_m, - num_threads, num_splits, partial_dtype, out_dtype, - has_cu_seqlens, - has_seqused, has_lse, - bool(return_temperature_lse), has_split_counts, - has_output_scale, use_pdl, - min_blocks_per_mp, - raw_partial_stats, + num_domains, + lse_split_aligned, ) if key not in _combine_compile_cache: loaded = try_load_aot(key) if loaded is not None: _combine_compile_cache[key] = loaded else: - from inference.msa_v1.attention.prefill._common.dsl.compile_utils import make_fake_tensor - kernel = SparseAttentionForwardCombine( dtype=out_dtype, dtype_partial=partial_dtype, - head_dim=D, - tile_m=tile_m, - k_block_size=k_block_size, + head_dim=dim, topk=num_splits, - num_threads=num_threads, - use_pdl=use_pdl, - min_blocks_per_mp=min_blocks_per_mp, + tile_m=TILE_M, + num_threads=NUM_THREADS, stages=stages, - raw_partial_stats=raw_partial_stats, + use_pdl=use_pdl, + num_domains=num_domains, + lse_split_aligned=lse_split_aligned, ) - div = 128 // partial_dtype.width - if has_cu_seqlens: - total_q, nheads = (cute.sym_int64() for _ in range(2)) - mO_partial = make_fake_tensor( - partial_dtype, (num_splits, total_q, nheads, D), divisibility=div - ) - mLSE_partial = make_fake_tensor( - Float32, - ( - (num_splits, total_q, nheads, 2) - if raw_partial_stats - else (num_splits, total_q, nheads) - ), - divisibility=2 if raw_partial_stats else 1, - leading_dim=3 if raw_partial_stats else 2, - ) - mO = make_fake_tensor( - out_dtype, (total_q, nheads, D), divisibility=128 // out_dtype.width - ) - mLSE = ( - make_fake_tensor(Float32, (total_q, nheads), divisibility=1, leading_dim=1) - if has_lse - else None - ) - mLSE_temperature_partial = ( - make_fake_tensor( - Float32, (num_splits, total_q, nheads), divisibility=1, leading_dim=2 - ) - if return_temperature_lse - else None - ) - mLSE_temperature = ( - make_fake_tensor(Float32, (total_q, nheads), divisibility=1, leading_dim=1) - if return_temperature_lse - else None - ) - else: - batch, sq, nheads = (cute.sym_int64() for _ in range(3)) - mO_partial = make_fake_tensor( - partial_dtype, (num_splits, batch, sq, nheads, D), divisibility=div - ) - mLSE_partial = make_fake_tensor( - Float32, (num_splits, batch, sq, nheads), divisibility=1, leading_dim=3 - ) - mO = make_fake_tensor( - out_dtype, (batch, sq, nheads, D), divisibility=128 // out_dtype.width - ) - mLSE = ( - make_fake_tensor(Float32, (batch, sq, nheads), divisibility=1, leading_dim=2) - if has_lse - else None - ) - mLSE_temperature_partial = ( - make_fake_tensor( - Float32, (num_splits, batch, sq, nheads), divisibility=1, leading_dim=3 - ) - if return_temperature_lse - else None - ) - mLSE_temperature = ( - make_fake_tensor(Float32, (batch, sq, nheads), divisibility=1, leading_dim=2) - if return_temperature_lse - else None - ) - if not has_split_counts: - mSplitCounts = None - elif has_cu_seqlens: - total_q_ctr, nheads_kv = (cute.sym_int64() for _ in range(2)) - mSplitCounts = make_fake_tensor( - Int32, (total_q_ctr, nheads_kv), divisibility=1, leading_dim=1 - ) - else: - nheads_kv = cute.sym_int64() - mSplitCounts = make_fake_tensor( - Int32, (batch, sq, nheads_kv), divisibility=1, leading_dim=2 + total_q_sym, nheads_sym = (cute.sym_int64() for _ in range(2)) + mO_partial = make_fake_tensor( + partial_dtype, + (num_splits, total_q_sym, nheads_sym, dim), + divisibility=128 // partial_dtype.width, + ) + mLSE_partial = make_fake_tensor( + Float32, (num_splits, total_q_sym, nheads_sym), divisibility=1, leading_dim=2 + ) + mO = make_fake_tensor( + out_dtype, (total_q_sym, nheads_sym, dim), divisibility=128 // out_dtype.width + ) + mLSE = ( + make_fake_tensor(Float32, (total_q_sym, nheads_sym), divisibility=1, leading_dim=1) + if has_lse + else None + ) + mSplitCounts = ( + make_fake_tensor( + Int32, (cute.sym_int64(), cute.sym_int64()), divisibility=1, leading_dim=1 ) - mOutputScale = ( - make_fake_tensor(Float32, (cute.sym_int64(),), divisibility=1, leading_dim=0) - if has_output_scale + if has_split_counts else None ) + mSmDomains, mTileCounters = ( + ( + make_fake_tensor(Int32, (cute.sym_int64(),), divisibility=1, leading_dim=0), + make_fake_tensor(Int32, (num_domains,), divisibility=1, leading_dim=0), + ) + if num_domains + else (None, None) + ) stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) - _combine_compile_cache[key] = compile_with_timing( kernel, mO_partial, mLSE_partial, mO, mLSE, - mLSE_temperature_partial, - mLSE_temperature, - None - if cu_seqlens is None - else make_fake_tensor(Int32, (cute.sym_int64(),), divisibility=1, leading_dim=0), - None - if seqused is None - else make_fake_tensor(Int32, (cute.sym_int64(),), divisibility=1, leading_dim=0), - None, - None, - None, mSplitCounts, - mOutputScale, - Int32(qheadperkv), + Int32(qhead_per_kvhead), + mSmDomains, + mTileCounters, + Int32(tiles_per_page_log2), stream, options="--enable-tvm-ffi", ) @@ -2345,14 +953,9 @@ def combine( lse_partial, o_out, lse_out, - lse_temperature_partial, - lse_temperature_out, - cu_seqlens, - seqused, - None, - None, - None, split_counts, - output_scale, - qheadperkv, + qhead_per_kvhead, + None if locality is None else locality.sm_domains, + None if locality is None else locality.tile_counters, + tiles_per_page_log2, ) diff --git a/inference/msa_v1/attention/prefill/_common/paged_interface.py b/inference/msa_v1/attention/prefill/_common/paged_interface.py index f87350dd..bcb9c755 100644 --- a/inference/msa_v1/attention/prefill/_common/paged_interface.py +++ b/inference/msa_v1/attention/prefill/_common/paged_interface.py @@ -326,10 +326,8 @@ def run( state.lse_partial, out_tensor, lse_tensor if return_lse or lse is not None else None, - cu_seqlens=state.metadata.cu_seqlens_q, split_counts=schedule.split_counts, use_pdl=True, - raw_partial_stats=False, ) if return_lse: return out_tensor, lse_tensor diff --git a/inference/msa_v1/attention/prefill/_common/vendor_manifest.json b/inference/msa_v1/attention/prefill/_common/vendor_manifest.json index 633e8891..a2a8bdfb 100644 --- a/inference/msa_v1/attention/prefill/_common/vendor_manifest.json +++ b/inference/msa_v1/attention/prefill/_common/vendor_manifest.json @@ -196,33 +196,6 @@ "destination": " )\n\n @cute.jit\n def apply_exp2_convert_fp16_mixed(\n self,\n acc_S_row: cute.Tensor,\n row_max: Float32,\n acc_S_row_converted: cute.Tensor,\n ) -> Float32:\n \"\"\"Rubin packed-FP16 exp/CVT for FP8 Q -> FP8 P, summing in FP32.\n\n Computation steps:\n\n * ``t = fma_f32x2(score, scale_log2, -row_max * scale_log2)`` in FP32\n (``cute.arch.fma_packed_f32x2``).\n * ``x = FP16(t)`` via ``cvt.rn.f16x2.f32`` -- the only rounding before\n the exponential, on the near-zero scaled difference.\n * ``p = exp2(x)`` via ``ex2.approx.f16x2``.\n * ``p = p * 448`` via ``mul.f16x2`` -- the FP8 probability scale, applied\n after the exponential (see below).\n * ``P = E4M3(p)`` via ``cvt.rn.satfinite.e4m3x2.f16x2``, four at a time.\n * Row sum: each scaled FP16 ``p`` pair is widened and accumulated in\n FP32 with ``add.f32x2.f16x2.f32x2`` into two independent accumulators\n combined with ``cute.arch.add_packed_f32x2``.\n\n The FP32 path folds ``log2(448)`` into the bias instead. Doing that here\n would push the exponent argument from ~0 to ~8.8, where FP16 spacing is\n ``2^-7`` rather than ``2^-11``: ``exp2(FP16(8.80735)) = 447.2``, not 448,\n which biases every ``p`` by ~0.2% and makes the single-token LSE\n ``ln(447.25/448) ~= -0.0017`` instead of exactly zero. Scaling after the\n exponential keeps the argument near zero, and ``exp2(0) * 448 == 448``\n exactly (448 = 1.75 * 2^8 is FP16-representable), so the row sum and\n LSE match the FP32 path in that case. Costs one ``HMUL2`` per pair.\n\n Only FP8 (E4M3) P is supported.\n \"\"\"\n assert cute.size(acc_S_row.shape) % 4 == 0\n assert cute.size(acc_S_row.shape) == cute.size(acc_S_row_converted.shape)\n assert acc_S_row_converted.element_type == cutlass.Float8E4M3FN, (\n \"packed FP16 softmax requires FP8 (E4M3) P\"\n )\n num_scores = cute.size(acc_S_row.shape)\n num_quads = num_scores // 4\n num_row_sum_accumulators = 2\n\n scale_log2_pair = (self.scale_log2, self.scale_log2)\n # No log2(448) in the bias: keep the FP16 exponent argument near zero\n # and apply the FP8 probability scale after the exponential instead.\n minus_row_max_scale = (Float32(0.0) - row_max) * self.scale_log2\n minus_row_max_scale_pair = (minus_row_max_scale, minus_row_max_scale)\n fp8_probability_scale = Float16(FP8_PROBABILITY_SCALE) # 448 = 1.75 * 2^8, exact in FP16\n fp8_probability_scale_pair = (fp8_probability_scale, fp8_probability_scale)\n\n # FP16 exp results and the FP8 P fragment, both viewed 4 at a time for\n # the E4M3 convert. The P view goes through the fragment's own layout\n # rather than recasting the whole fragment to Int32 and\n # indexing linearly, so no assumption is made about its contiguity.\n exp_buf = cute.make_rmem_tensor(cute.make_layout(num_scores), Float16)\n exp_buf_cvt = cute.logical_divide(exp_buf, cute.make_layout(4))\n p_cvt = cute.logical_divide(acc_S_row_converted, cute.make_layout(4))\n\n row_sums = [(Float32(0.0), Float32(0.0)) for _ in range(num_row_sum_accumulators)]\n\n for i in cutlass.range_constexpr(0, num_scores, 2):\n # Stage 1: full FP32 affine transform.\n scaled_pair = cute.arch.fma_packed_f32x2(\n (acc_S_row[i], acc_S_row[i + 1]),\n scale_log2_pair,\n minus_row_max_scale_pair,\n )\n # Stage 2: round the pair to packed FP16.\n packed_pair = cvt_packed_f16x2_f32x2(scaled_pair)\n # Stage 3: packed exponential, then the FP8 probability scale.\n exp_pair = mul_packed_f16x2(\n ex2_packed_f16x2(packed_pair), fp8_probability_scale_pair\n )\n exp_buf[i] = exp_pair[0]\n exp_buf[i + 1] = exp_pair[1]\n # FP32 row sum of the scaled values, widening the FP16 pair on the fly.\n sum_slot = (i // 2) % num_row_sum_accumulators\n row_sums[sum_slot] = add_packed_f32x2_f16x2_f32x2(exp_pair, row_sums[sum_slot])\n\n # E4M3 convert, four FP16 values -> four FP8 P values, per quad slice.\n for q in cutlass.range_constexpr(num_quads):\n cvt_f16x4_to_f8x4(exp_buf_cvt[None, q], p_cvt[None, q])\n\n local_row_sum = cute.arch.add_packed_f32x2(row_sums[0], row_sums[1])\n return local_row_sum[0] + local_row_sum[1]\n\n @cute.jit\n def scale_apply_exp2_convert(\n self,\n acc_S_row: cute.Tensor,\n", "reason": "保留 nv_dev 已有 SM107 Rubin 架构分支,Blackwell 路径不变。" } - ], - "attention/fwd/combine.py": [ - { - "source": "import cutlass\nfrom cutlass import Boolean, Float32, Int32, Int64, const_expr\nimport cutlass.cute as cute\nfrom cutlass.cute import FastDivmodDivisor\nfrom cutlass.cute.nvgpu import cpasync\nimport cuda.bindings.driver as cuda\n", - "destination": "import cutlass\nfrom cutlass import Boolean, Float32, Int32, Int64, const_expr\nimport cutlass.cute as cute\nfrom cutlass.cutlass_dsl import BaseDSL\nfrom cutlass.cute import FastDivmodDivisor\nfrom cutlass.cute.nvgpu import cpasync\nimport cuda.bindings.driver as cuda\n", - "reason": "保留 nv_dev 已有 SM107 Rubin 架构分支,Blackwell 路径不变。" - }, - { - "source": " self.num_threads = num_threads\n self.is_even_k = head_dim % k_block_size == 0\n self.stages = stages\n self.use_pdl = use_pdl\n self.min_blocks_per_mp = min_blocks_per_mp\n self.raw_partial_stats = raw_partial_stats\n", - "destination": " self.num_threads = num_threads\n self.is_even_k = head_dim % k_block_size == 0\n self.stages = stages\n arch = BaseDSL._get_dsl().get_arch_enum()\n rubin_arch = getattr(arch.__class__, \"sm_107\", None)\n self.is_rubin = rubin_arch is not None and arch.is_family_of(rubin_arch)\n self.use_pdl = use_pdl\n self.min_blocks_per_mp = min_blocks_per_mp\n self.raw_partial_stats = raw_partial_stats\n", - "reason": "保留 nv_dev 已有 SM107 Rubin 架构分支,Blackwell 路径不变。" - }, - { - "source": " # Get scales for this split\n scale = cute.make_rmem_tensor(num_rows, Float32)\n for m in cutlass.range(num_rows, unroll_full=True):\n scale[m] = sLSE[s, tOcO[0, m, 0][0]] # Get scale from smem\n\n if const_expr(self.use_tma_partial):\n cute.autovec_copy(\n", - "destination": " # Get scales for this split\n scale = cute.make_rmem_tensor(num_rows, Float32)\n for m in cutlass.range(num_rows, unroll_full=True):\n scale[m] = sLSE[s, tOcO[0, m, 0][0]]\n\n if const_expr(self.use_tma_partial):\n cute.autovec_copy(\n", - "reason": "保留 nv_dev 已有 SM107 Rubin 架构分支,Blackwell 路径不变。" - }, - { - "source": " has_output_scale = output_scale is not None\n min_blocks_per_mp = 3 if has_output_scale and use_pdl else 0\n\n key = (\n \"combine\",\n D,\n k_block_size,\n tile_m,\n", - "destination": " has_output_scale = output_scale is not None\n min_blocks_per_mp = 3 if has_output_scale and use_pdl else 0\n\n capability = torch.cuda.get_device_capability(o_out.device)\n stages = 4 if capability == (10, 7) else 2\n key = (\n \"combine\",\n capability,\n stages,\n D,\n k_block_size,\n tile_m,\n", - "reason": "保留 nv_dev 已有 SM107 Rubin 架构分支,Blackwell 路径不变。" - }, - { - "source": " num_threads=num_threads,\n use_pdl=use_pdl,\n min_blocks_per_mp=min_blocks_per_mp,\n stages=2,\n raw_partial_stats=raw_partial_stats,\n )\n div = 128 // partial_dtype.width\n", - "destination": " num_threads=num_threads,\n use_pdl=use_pdl,\n min_blocks_per_mp=min_blocks_per_mp,\n stages=stages,\n raw_partial_stats=raw_partial_stats,\n )\n div = 128 // partial_dtype.width\n", - "reason": "保留 nv_dev 已有 SM107 Rubin 架构分支,Blackwell 路径不变。" - } ] }, "organization_files": [ @@ -232,7 +205,8 @@ "atten_fwd_sm100.py", "paged_interface.py", "dsl/rubin_helpers.py", - "dsl/rubin_softmax_helpers.py" + "dsl/rubin_softmax_helpers.py", + "combine.py" ], "files": [ { @@ -299,10 +273,6 @@ "source": "_common/utils.py", "destination": "dsl/utils.py" }, - { - "source": "attention/fwd/combine.py", - "destination": "combine.py" - }, { "source": "attention/metadata.py", "destination": "metadata.py" diff --git a/inference/msa_v1/attention/prefill/q8kv4/README.md b/inference/msa_v1/attention/prefill/q8kv4/README.md index 3cee053d..6de8af90 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/README.md +++ b/inference/msa_v1/attention/prefill/q8kv4/README.md @@ -4,8 +4,8 @@ ## Purpose -Paged sparse causal prefill attention for SM100 and SM103. Q uses E4M3, K/V use packed E2M1 -with E4M3 scales, the output uses BF16, and varlen chunk prefill is supported. +Paged sparse causal prefill attention for SM100, SM103 and SM107. Q uses E4M3, K/V use packed +E2M1 with E4M3 scales, the output uses BF16, and varlen chunk prefill is supported. Attention probabilities use `E4M3(P * 448)` with compensation during normalization. Returned LSE retains the natural-log semantics of the original logits. Probability @@ -16,6 +16,7 @@ quantization follows decode semantics; final outputs are not guaranteed bitwise ```python from inference.msa_v1.attention.prefill.q8kv4 import ( BatchPrefillWithPagedKVCacheWrapper, + PrefillWorkspace, ) wrapper = BatchPrefillWithPagedKVCacheWrapper() @@ -39,6 +40,28 @@ out, lse = wrapper.run( Callers may pass preallocated `out` and `lse` tensors to `run()`. +### Split workspace + +The forward writes one partial output and LSE per (query, head, selected page) and the combine +merges them. `PrefillWorkspace` owns those buffers. A wrapper creates its own in `plan()`; +wrappers that run in order on one stream may share one passed to the constructor, and +`partial_bytes` reserves the largest batch up front: + +```python +workspace = PrefillWorkspace(device) +workspace = PrefillWorkspace( + device, partial_bytes=workspace.required_bytes(max_total_q, num_q_heads) +) +wrapper = BatchPrefillWithPagedKVCacheWrapper(workspace) +``` + +On a GPU with several memory locality domains (Rubin uGPU, Blackwell) the workspace stripes the +partial buffer over the domains and the combine reads every tile from the domain of its own SM; +the results are the same as with interleaved memory. A batch that outgrows a striped buffer +synchronizes the device before replacing it, so reserve the largest batch before CUDA Graph +capture. `MM_SPARSE_PREFILL_Q8KV4_LOCALITY_DOMAINS=0` keeps the buffer interleaved (for +comparisons). One workspace must not be used from two streams at once. + ## Data contract - `q`: `[total_q, Hq, 128]`, E4M3; `Hq = 16 * Hkv`. @@ -60,7 +83,8 @@ Callers may pass preallocated `out` and `lse` tensors to `run()`. heads are supported without head replication. - `cu_seqlens_k` is the only source of KV lengths. - Call `plan()` outside CUDA Graph capture and preallocate `out` and `lse` during capture. -- NVFP4 dequantization requires CUDA Toolkit 13.4 or newer. +- CUDA Toolkit 13.4 or newer is required; SM107 requires 13.5 or newer. NVFP4 dequantization + uses QMUL4 where the toolchain provides it and an exact packed-FP16 path otherwise (SM107). ## Cache layout diff --git a/inference/msa_v1/attention/prefill/q8kv4/README.zh-CN.md b/inference/msa_v1/attention/prefill/q8kv4/README.zh-CN.md index b33c876c..3b15cc73 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/README.zh-CN.md +++ b/inference/msa_v1/attention/prefill/q8kv4/README.zh-CN.md @@ -4,7 +4,7 @@ ## 功能 -面向 SM100/SM103 的 paged sparse causal prefill attention。Q 使用 E4M3,K/V 使用 +面向 SM100/SM103/SM107 的 paged sparse causal prefill attention。Q 使用 E4M3,K/V 使用 packed E2M1 和 E4M3 scale,输出为 BF16,并支持 varlen chunk prefill。 Attention 概率按 `E4M3(P × 448)` 量化,并在归一化时补偿该缩放;返回的 LSE @@ -15,6 +15,7 @@ Attention 概率按 `E4M3(P × 448)` 量化,并在归一化时补偿该缩放 ```python from inference.msa_v1.attention.prefill.q8kv4 import ( BatchPrefillWithPagedKVCacheWrapper, + PrefillWorkspace, ) wrapper = BatchPrefillWithPagedKVCacheWrapper() @@ -38,6 +39,27 @@ out, lse = wrapper.run( 调用方可以向 `run()` 传入预分配的 `out` 和 `lse`。 +### Split workspace + +forward 为每个 (query, head, 选中页) 写出一份 partial output 和 LSE,由 combine 合并。 +`PrefillWorkspace` 持有这些 buffer。wrapper 默认在 `plan()` 中创建自己的 workspace;在同一 +stream 上顺序执行的多个 wrapper 可以共享构造时传入的同一个 workspace,`partial_bytes` 可按 +最大 batch 预留: + +```python +workspace = PrefillWorkspace(device) +workspace = PrefillWorkspace( + device, partial_bytes=workspace.required_bytes(max_total_q, num_q_heads) +) +wrapper = BatchPrefillWithPagedKVCacheWrapper(workspace) +``` + +在具有多个 memory locality domain 的 GPU(Rubin uGPU、Blackwell)上,workspace 将 partial +buffer 按 domain 条带化,combine 的每个 tile 都从其所在 SM 的 domain 读取;结果与 interleaved +内存完全一致。batch 超出已条带化的 buffer 时会先同步设备再替换,因此应在 CUDA Graph capture +前按最大 batch 预留。`MM_SPARSE_PREFILL_Q8KV4_LOCALITY_DOMAINS=0` 保持 interleaved 布局 +(用于对比)。同一个 workspace 不得同时用于两个 stream。 + ## 数据契约 - `q`:`[total_q, Hq, 128]`,E4M3;`Hq = 16 * Hkv`。 @@ -55,7 +77,8 @@ out, lse = wrapper.run( - head 数由 TopK 的首维确定,支持 64/4 和 16/1 本地 query/KV heads,无需复制 heads。 - `cu_seqlens_k` 是 KV 长度的唯一来源。 - `plan()` 必须在 CUDA Graph capture 外调用;capture 时应预分配 `out` 和 `lse`。 -- NVFP4 dequant 要求 CUDA Toolkit 13.4 或更高版本。 +- 要求 CUDA Toolkit 13.4 或更高版本;SM107 要求 13.5 或更高版本。NVFP4 dequant 在工具链 + 支持时使用 QMUL4,否则(SM107)使用精确的 packed-FP16 路径。 ## Cache 布局 diff --git a/inference/msa_v1/attention/prefill/q8kv4/__init__.py b/inference/msa_v1/attention/prefill/q8kv4/__init__.py index 2a0e8ccd..7777b3e7 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/__init__.py +++ b/inference/msa_v1/attention/prefill/q8kv4/__init__.py @@ -2,6 +2,7 @@ from inference.msa_v1.attention.prefill.q8kv4.interface import ( BatchPrefillWithPagedKVCacheWrapper, + PrefillWorkspace, ) -__all__ = ["BatchPrefillWithPagedKVCacheWrapper"] +__all__ = ["BatchPrefillWithPagedKVCacheWrapper", "PrefillWorkspace"] diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/api/locality_domains.cu b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/locality_domains.cu new file mode 100644 index 00000000..e3e4e859 --- /dev/null +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/locality_domains.cu @@ -0,0 +1,305 @@ +// Memory locality domains (Rubin uGPU, Blackwell's dies): the domain of every SM, and +// partial-output buffers whose pages alternate between the domains so a CTA can read its tile +// from the domain of its own SM. Devices with one domain report a count of 1 and the callers keep +// ordinary allocations. + +#include "prefill_attention_api.hpp" + +#include +#include +#include +#include + +#include +#include + +// The locality-domain driver API ships with CUDA 13.4. +#if CUDA_VERSION >= 13040 +#define MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS 1 +#else +#define MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS 0 +#endif + +namespace minimax::msa_v1::attention::prefill::q8kv4 { +namespace { + +int checked_device(int64_t device) { + int count = 0; + C10_CUDA_CHECK(cudaGetDeviceCount(&count)); + TORCH_CHECK(device >= 0 && device < count, "device ordinal ", device, " out of range"); + return static_cast(device); +} + +#if MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS + +void check_driver(CUresult result, char const *what) { + if (result != CUDA_SUCCESS) { + char const *message = nullptr; + cuGetErrorString(result, &message); + TORCH_CHECK(false, what, " failed: ", message ? message : "unknown CUDA driver error"); + } +} + +CUdevice driver_device(int device) { + check_driver(cuInit(0), "cuInit"); + CUdevice cu_device; + check_driver(cuDeviceGet(&cu_device, device), "cuDeviceGet"); + return cu_device; +} + +// cuDevSmResourceSplit is a CUDA 13.4 driver entry point. Resolving it at run time keeps this +// extension loadable on older drivers (CUDA 13.0 to 13.3), where locality-domain striping is simply +// unavailable; the green-context and virtual-memory calls below predate it. +decltype(&cuDevSmResourceSplit) sm_resource_split() { + static decltype(&cuDevSmResourceSplit) const function = [] { + void *address = nullptr; + CUdriverProcAddressQueryResult status = CU_GET_PROC_ADDRESS_SUCCESS; + CUresult const result = cuGetProcAddress("cuDevSmResourceSplit", &address, 13040, + CU_GET_PROC_ADDRESS_DEFAULT, &status); + return result == CUDA_SUCCESS && status == CU_GET_PROC_ADDRESS_SUCCESS + ? reinterpret_cast(address) + : nullptr; + }(); + return function; +} + +int domain_count(int device) { + if (sm_resource_split() == nullptr) { + return 1; + } + int count = 0; + CUresult const result = cuDeviceGetAttribute(&count, CU_DEVICE_ATTRIBUTE_LOCALITY_DOMAIN_COUNT, + driver_device(device)); + // Drivers without the attribute expose one domain. + return result == CUDA_SUCCESS && count > 1 ? count : 1; +} + +CUmemAllocationProp localized_prop(int device, int domain) { + CUmemAllocationProp prop{}; + prop.type = CU_MEM_ALLOCATION_TYPE_PINNED; + prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN; + prop.location.localized.deviceId = static_cast(device); + prop.location.localized.localityDomainId = static_cast(domain); + return prop; +} + +size_t page_bytes(int device) { + CUmemAllocationProp const prop = localized_prop(device, 0); + size_t granularity = 0; + check_driver(cuMemGetAllocationGranularity(&granularity, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM), + "cuMemGetAllocationGranularity"); + return granularity; +} + +// Every CTA records the SM it runs on. The shared-memory request admits one CTA per SM and the +// spin outlasts the dispatch of the whole grid, so the first wave covers every SM of the stream's +// green context. +__global__ void record_sm_ids(int32_t *sm_ids, int32_t *sm_id_count, long long spin_cycles) { + if (threadIdx.x == 0) { + unsigned int sm_id; + asm volatile("mov.u32 %0, %%smid;" : "=r"(sm_id)); + sm_ids[blockIdx.x] = static_cast(sm_id); + if (blockIdx.x == 0) { + unsigned int count; + asm volatile("mov.u32 %0, %%nsmid;" : "=r"(count)); + *sm_id_count = static_cast(count); + } + long long const start = clock64(); + while (clock64() - start < spin_cycles) { + } + } +} + +// A green context over one locality domain's SMs and a stream on it. +struct DomainContext { + CUgreenCtx context = nullptr; + CUstream stream = nullptr; + + DomainContext(CUdevice device, CUdevResource const &resource) { + CUdevResourceDesc descriptor; + check_driver(cuDevResourceGenerateDesc(&descriptor, const_cast(&resource), 1), + "cuDevResourceGenerateDesc"); + check_driver(cuGreenCtxCreate(&context, descriptor, device, CU_GREEN_CTX_DEFAULT_STREAM), + "cuGreenCtxCreate"); + check_driver(cuGreenCtxStreamCreate(&stream, context, CU_STREAM_NON_BLOCKING, 0), + "cuGreenCtxStreamCreate"); + } + DomainContext(DomainContext const &) = delete; + DomainContext &operator=(DomainContext const &) = delete; + ~DomainContext() { + if (stream != nullptr) { + cuStreamDestroy(stream); + } + if (context != nullptr) { + cuGreenCtxDestroy(context); + } + } +}; + +std::vector split_sms_by_domain(CUdevice cu_device, int num_domains) { + CUdevResource all_sms{}; + check_driver(cuDeviceGetDevResource(cu_device, &all_sms, CU_DEV_RESOURCE_TYPE_SM), + "cuDeviceGetDevResource"); + std::vector group_params(num_domains); + for (int domain = 0; domain < num_domains; ++domain) { + group_params[domain] = CU_DEV_SM_RESOURCE_GROUP_PARAMS{}; + group_params[domain].coscheduledSmCount = 2; + group_params[domain].flags = CU_DEV_SM_RESOURCE_GROUP_LOCALITY_DOMAIN_ID; + group_params[domain].localityDomainId = static_cast(domain); + } + std::vector groups(num_domains); + CUdevResource remainder{}; + check_driver(sm_resource_split()(groups.data(), static_cast(num_domains), &all_sms, + &remainder, 0, group_params.data()), + "cuDevSmResourceSplit"); + return groups; +} + +#endif // MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS + +} // namespace + +int64_t locality_domain_count(int64_t device) { + int const index = checked_device(device); +#if MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS + return domain_count(index); +#else + (void)index; + return 1; +#endif +} + +int64_t locality_page_bytes(int64_t device) { + int const index = checked_device(device); +#if MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS + return static_cast(page_bytes(index)); +#else + (void)index; + TORCH_CHECK(false, "locality domains need a CUDA 13.4 or newer toolkit"); +#endif +} + +std::vector sm_locality_domains(int64_t device) { + int const index = checked_device(device); +#if MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS + c10::cuda::CUDAGuard const device_guard(index); + CUdevice const cu_device = driver_device(index); + int const num_domains = domain_count(index); + + std::vector const groups = split_sms_by_domain(cu_device, num_domains); + + int clock_khz = 0; + C10_CUDA_CHECK(cudaDeviceGetAttribute(&clock_khz, cudaDevAttrClockRate, index)); + int smem_per_block = 0; + C10_CUDA_CHECK( + cudaDeviceGetAttribute(&smem_per_block, cudaDevAttrMaxSharedMemoryPerBlockOptin, index)); + C10_CUDA_CHECK(cudaFuncSetAttribute(record_sm_ids, cudaFuncAttributeMaxDynamicSharedMemorySize, + smem_per_block)); + // Two waves of one CTA per SM; the spin lasts longer than dispatching them. + long long const spin_cycles = static_cast(clock_khz) * 2; + auto const options = torch::TensorOptions().dtype(torch::kInt32).device(torch::kCUDA, index); + torch::Tensor const sm_id_count = torch::zeros({1}, options); + + torch::Tensor table; + for (int domain = 0; domain < num_domains; ++domain) { + unsigned int const sm_count = groups[domain].sm.smCount; + if (sm_count == 0) { + continue; + } + DomainContext const context(cu_device, groups[domain]); + int const ctas = static_cast(sm_count) * 2; + torch::Tensor const sm_ids = torch::full({ctas}, -1, options); + record_sm_ids<<(context.stream)>>>( + sm_ids.data_ptr(), sm_id_count.data_ptr(), spin_cycles); + C10_CUDA_CHECK(cudaGetLastError()); + C10_CUDA_CHECK(cudaStreamSynchronize(static_cast(context.stream))); + if (!table.defined()) { + table = torch::full({sm_id_count.item()}, -1, torch::dtype(torch::kInt32)); + } + auto const ids = sm_ids.cpu(); + auto const ids_accessor = ids.accessor(); + auto table_accessor = table.accessor(); + for (int cta = 0; cta < ctas; ++cta) { + int32_t const sm_id = ids_accessor[cta]; + if (sm_id >= 0 && sm_id < table.size(0)) { + table_accessor[sm_id] = domain; + } + } + } + TORCH_CHECK(table.defined(), "no locality domain exposes any SM"); + auto const table_accessor = table.accessor(); + std::vector domains(table.size(0)); + for (int64_t sm_id = 0; sm_id < table.size(0); ++sm_id) { + domains[sm_id] = table_accessor[sm_id]; + } + return domains; +#else + (void)index; + TORCH_CHECK(false, "locality domains need a CUDA 13.4 or newer toolkit"); +#endif +} + +torch::Tensor alloc_locality_striped(int64_t bytes, int64_t device) { + int const index = checked_device(device); +#if MINIMAX_MSA_PREFILL_Q8KV4_HAS_LOCALITY_DOMAINS + c10::cuda::CUDAGuard const device_guard(index); + int const num_domains = domain_count(index); + size_t const page = page_bytes(index); + TORCH_CHECK(bytes > 0 && static_cast(bytes) % (page * num_domains) == 0, + "a striped buffer must hold a multiple of ", num_domains, " x ", page, " bytes"); + struct Mapping { + CUdeviceptr base = 0; + size_t bytes = 0; + std::vector handles; + }; + auto release = [](Mapping const &mapping) { + if (mapping.base != 0) { + cuMemUnmap(mapping.base, mapping.bytes); + cuMemAddressFree(mapping.base, mapping.bytes); + } + for (CUmemGenericAllocationHandle const handle : mapping.handles) { + cuMemRelease(handle); + } + }; + + Mapping mapping; + mapping.bytes = static_cast(bytes); + try { + check_driver(cuMemAddressReserve(&mapping.base, mapping.bytes, page, 0, 0), + "cuMemAddressReserve"); + // cuMemMap maps a handle from its start, so every page is its own allocation. + size_t const pages = mapping.bytes / page; + mapping.handles.reserve(pages); + for (size_t p = 0; p < pages; ++p) { + CUmemAllocationProp const prop = localized_prop(index, static_cast(p % num_domains)); + CUmemGenericAllocationHandle handle; + check_driver(cuMemCreate(&handle, page, &prop, 0), "cuMemCreate"); + mapping.handles.push_back(handle); + check_driver(cuMemMap(mapping.base + p * page, page, 0, handle, 0), "cuMemMap"); + } + CUmemAccessDesc access{}; + access.location.type = CU_MEM_LOCATION_TYPE_DEVICE; + access.location.id = index; + access.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE; + check_driver(cuMemSetAccess(mapping.base, mapping.bytes, &access, 1), "cuMemSetAccess"); + } catch (...) { + release(mapping); + throw; + } + + // The last reference may drop while a kernel still reads the buffer (a workspace replaced by + // a larger one, or its owner destroyed): finish the device's work before unmapping. + auto deleter = [mapping, release](void *) { + cudaDeviceSynchronize(); + release(mapping); + }; + auto const options = torch::TensorOptions().dtype(torch::kUInt8).device(torch::kCUDA, index); + return torch::from_blob(reinterpret_cast(mapping.base), {bytes}, deleter, options); +#else + (void)index; + (void)bytes; + TORCH_CHECK(false, "locality domains need a CUDA 13.4 or newer toolkit"); +#endif +} + +} // namespace minimax::msa_v1::attention::prefill::q8kv4 diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.cpp b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.cpp index 3e946f40..333a40e9 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.cpp +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.cpp @@ -67,16 +67,16 @@ void prefill_run(torch::Tensor q, torch::Tensor packed_k, torch::Tensor packed_v torch::Tensor cu_seqlens_q, torch::Tensor cu_seqlens_k, torch::Tensor k2q_row_ptr, torch::Tensor qsplit_indices, torch::Tensor scheduler_metadata, torch::Tensor work_count, torch::Tensor o_partial, torch::Tensor lse_partial, - double softmax_scale) { + double softmax_scale, c10::optional combine_tile_counters) { torch::Tensor tensors[] = { q, page_table, cu_seqlens_q, cu_seqlens_k, k2q_row_ptr, qsplit_indices, scheduler_metadata, work_count, - o_partial, lse_partial, + lse_partial, }; char const *names[] = { "q", "page_table", "cu_seqlens_q", "cu_seqlens_k", "k2q_row_ptr", "qsplit_indices", "scheduler_metadata", "work_count", - "o_partial", "lse_partial", + "lse_partial", }; constexpr std::size_t kTensorCount = sizeof(tensors) / sizeof(tensors[0]); static_assert(kTensorCount == sizeof(names) / sizeof(names[0])); @@ -96,6 +96,10 @@ void prefill_run(torch::Tensor q, torch::Tensor packed_k, torch::Tensor packed_v } TORCH_CHECK(packed_v.strides() == packed_k.strides() && v_scale.strides() == k_scale.strides(), "K/V cache strides and K/V scale strides must match"); + // The split slabs of o_partial may be padded apart (locality-domain striping); rows inside a + // slab are contiguous. + TORCH_CHECK(o_partial.is_cuda(), "o_partial must be a CUDA tensor"); + check_same_device(q, o_partial, "o_partial"); TORCH_CHECK(q.scalar_type() == at::kFloat8_e4m3fn, "q must have dtype torch.float8_e4m3fn"); TORCH_CHECK(packed_k.scalar_type() == at::kByte && packed_v.scalar_type() == at::kByte, @@ -147,6 +151,14 @@ void prefill_run(torch::Tensor q, torch::Tensor packed_k, torch::Tensor packed_v o_partial.size(1) == total_q_64 && o_partial.size(2) == num_q_heads && o_partial.size(3) == kHeadDim, "o_partial must have shape [16, total_q, num_q_heads, 128]"); + int64_t const slab_elements = total_q_64 * num_q_heads * kHeadDim; + TORCH_CHECK(o_partial.stride(3) == 1 && o_partial.stride(2) == kHeadDim && + o_partial.stride(1) == static_cast(num_q_heads) * kHeadDim, + "o_partial rows must be contiguous inside each split slab"); + TORCH_CHECK(o_partial.stride(0) >= slab_elements && o_partial.stride(0) % 8 == 0, + "o_partial split stride must cover a slab and keep 16-byte alignment"); + TORCH_CHECK(reinterpret_cast(o_partial.data_ptr()) % 16 == 0, + "o_partial must be 16-byte aligned"); TORCH_CHECK(lse_partial.dim() == 3 && lse_partial.size(0) == kTopK && lse_partial.size(1) == total_q_64 && lse_partial.size(2) == num_q_heads, "lse_partial must have shape [16, total_q, num_q_heads]"); @@ -155,8 +167,9 @@ void prefill_run(torch::Tensor q, torch::Tensor packed_k, torch::Tensor packed_v c10::cuda::CUDAGuard const device_guard(q.device()); cudaDeviceProp const *properties = at::cuda::getCurrentDeviceProperties(); - TORCH_CHECK(properties->major == 10 && (properties->minor == 0 || properties->minor == 3), - "Q8KV4 sparse prefill requires an SM100-family GPU"); + TORCH_CHECK(properties->major == 10 && + (properties->minor == 0 || properties->minor == 3 || properties->minor == 7), + "Q8KV4 sparse prefill requires an SM100, SM103 or SM107 GPU"); PrefillArguments arguments{}; arguments.q_ptr = reinterpret_cast(q.data_ptr()); @@ -173,7 +186,18 @@ void prefill_run(torch::Tensor q, torch::Tensor packed_k, torch::Tensor packed_v arguments.work_count_ptr = work_count.data_ptr(); arguments.o_partial_ptr = reinterpret_cast(o_partial.data_ptr()); + arguments.o_partial_split_stride = o_partial.stride(0); arguments.lse_partial_ptr = lse_partial.data_ptr(); + if (combine_tile_counters.has_value()) { + check_cuda_contiguous(*combine_tile_counters, "combine_tile_counters"); + check_same_device(q, *combine_tile_counters, "combine_tile_counters"); + TORCH_CHECK(combine_tile_counters->scalar_type() == at::kInt && + combine_tile_counters->dim() == 1 && combine_tile_counters->numel() >= 1, + "combine_tile_counters must be a one-dimensional int32 tensor"); + arguments.combine_tile_counters_ptr = combine_tile_counters->data_ptr(); + arguments.combine_tile_counter_count = + checked_int_dimension(combine_tile_counters->numel(), "combine_tile_counters"); + } arguments.total_q = total_q; arguments.num_q_heads = num_q_heads; arguments.num_kv_heads = num_kv_heads; diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.hpp b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.hpp index 1604cc40..a3988568 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.hpp +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_api.hpp @@ -2,22 +2,29 @@ #include +#include +#include + namespace minimax::msa_v1::attention::prefill::q8kv4 { -void prefill_run(torch::Tensor q, - torch::Tensor packed_k, - torch::Tensor packed_v, - torch::Tensor k_scale, - torch::Tensor v_scale, - torch::Tensor page_table, - torch::Tensor cu_seqlens_q, - torch::Tensor cu_seqlens_k, - torch::Tensor k2q_row_ptr, - torch::Tensor qsplit_indices, - torch::Tensor scheduler_metadata, - torch::Tensor work_count, - torch::Tensor o_partial, - torch::Tensor lse_partial, - double softmax_scale); +void prefill_run(torch::Tensor q, torch::Tensor packed_k, torch::Tensor packed_v, + torch::Tensor k_scale, torch::Tensor v_scale, torch::Tensor page_table, + torch::Tensor cu_seqlens_q, torch::Tensor cu_seqlens_k, torch::Tensor k2q_row_ptr, + torch::Tensor qsplit_indices, torch::Tensor scheduler_metadata, + torch::Tensor work_count, torch::Tensor o_partial, torch::Tensor lse_partial, + double softmax_scale, + c10::optional combine_tile_counters = c10::nullopt); + +// Memory locality domains of a device (Rubin uGPU, Blackwell's dies; one elsewhere). +int64_t locality_domain_count(int64_t device); +// Allocation granularity of domain-localized memory, the page at which a striped buffer +// alternates domains. +int64_t locality_page_bytes(int64_t device); +// The locality domain of every SM id (%smid), -1 where unknown. +std::vector sm_locality_domains(int64_t device); +// A uint8 device buffer whose pages alternate between the locality domains: page p (of +// locality_page_bytes) lives in domain p % locality_domain_count. bytes must be a multiple of +// the page size times the domain count. +torch::Tensor alloc_locality_striped(int64_t bytes, int64_t device); -} // namespace minimax::msa_v1::attention::prefill::q8kv4 +} // namespace minimax::msa_v1::attention::prefill::q8kv4 diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_binding.cpp b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_binding.cpp index 476a7ef8..109e3b0f 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_binding.cpp +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/api/prefill_attention_binding.cpp @@ -2,8 +2,22 @@ #include "prefill_attention_api.hpp" +namespace q8kv4 = minimax::msa_v1::attention::prefill::q8kv4; + PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) { - module.def( - "run", &minimax::msa_v1::attention::prefill::q8kv4::prefill_run, - "SM100 Q8KV4 paged sparse-prefill K1"); + module.def("run", &q8kv4::prefill_run, "SM100 Q8KV4 paged sparse-prefill K1", py::arg("q"), + py::arg("packed_k"), py::arg("packed_v"), py::arg("k_scale"), py::arg("v_scale"), + py::arg("page_table"), py::arg("cu_seqlens_q"), py::arg("cu_seqlens_k"), + py::arg("k2q_row_ptr"), py::arg("qsplit_indices"), py::arg("scheduler_metadata"), + py::arg("work_count"), py::arg("o_partial"), py::arg("lse_partial"), + py::arg("softmax_scale"), py::arg("combine_tile_counters") = py::none()); + module.def("locality_domain_count", &q8kv4::locality_domain_count, + "Memory locality domains of a device", py::arg("device")); + module.def("locality_page_bytes", &q8kv4::locality_page_bytes, + "Allocation granularity of domain-localized memory", py::arg("device")); + module.def("sm_locality_domains", &q8kv4::sm_locality_domains, + "Locality domain of every SM id, -1 where unknown", py::arg("device")); + module.def("alloc_locality_striped", &q8kv4::alloc_locality_striped, + "Device buffer whose pages alternate between the locality domains", py::arg("bytes"), + py::arg("device")); } diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_fp4_transform.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_fp4_transform.cuh index d8c3886c..ca8c6e0e 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_fp4_transform.cuh +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_fp4_transform.cuh @@ -9,27 +9,17 @@ namespace minimax::msa_v1::attention::prefill::q8kv4::detail { -CUTLASS_DEVICE void dequant_e2m1x8_uniform_scale( - uint32_t& output_lo, uint32_t& output_hi, - uint32_t packed_fp4, uint32_t scale_e4m3x4) { - ::minimax::msa_v1::attention::prefill::q8kv4::sm100::common:: - nvfp4_to_e4m3x4( - output_lo, static_cast(packed_fp4), scale_e4m3x4); - ::minimax::msa_v1::attention::prefill::q8kv4::sm100::common:: - nvfp4_to_e4m3x4( - output_hi, static_cast(packed_fp4 >> 16), scale_e4m3x4); -} - struct Fp4DequantInput { uint32_t packed_fp4; - uint32_t scale_e4m3x4; + uint32_t scale_word; }; CUTLASS_DEVICE Fp4DequantInput load_fp4_dequant_input( uint8_t const* packed_fp4, uint8_t scale_e4m3) { return { *reinterpret_cast(packed_fp4), - static_cast(scale_e4m3) * 0x01010101u, + ::minimax::msa_v1::attention::prefill::q8kv4::sm100::common:: + make_dequant_scale_word(scale_e4m3), }; } @@ -37,8 +27,9 @@ CUTLASS_DEVICE void dequant_store_fp8_smem( Fp4DequantInput const& input, uint32_t output_address) { uint32_t output_lo; uint32_t output_hi; - dequant_e2m1x8_uniform_scale( - output_lo, output_hi, input.packed_fp4, input.scale_e4m3x4); + ::minimax::msa_v1::attention::prefill::q8kv4::sm100::common:: + dequant_e2m1x8_uniform_scale( + output_lo, output_hi, input.packed_fp4, input.scale_word); asm volatile("st.shared.v2.b32 [%0], {%1, %2};" : : "r"(output_address), "r"(output_lo), "r"(output_hi)); diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_mainloop.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_mainloop.cuh index bec7b5a2..d0ed12d6 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_mainloop.cuh +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/collective/sm100_prefill_attention_mainloop.cuh @@ -156,30 +156,50 @@ CUTLASS_DEVICE void run_load_warps(Storage &storage, Params const ¶ms, int w cute::prefetch_tma_descriptor(tma_q.get_tma_descriptor()); } + // The packed query indices are fetched kQsplitPrefetchGroups groups at a time (one coalesced + // warp load) into the metadata ring, so the per-group loop carries no dependent global load. + // Slot g % kQMetadataStages was last used by group g - kQMetadataStages, whose consumers are + // done by then: the epilogue trails the loader by at most kQStages + kScoreStages groups. + constexpr int kQsplitPrefetchGroups = 8; + static_assert(kQsplitPrefetchGroups * kQueriesPerGroup == 2 * 32); + static_assert(kQsplitPrefetchGroups + kQStages + kScoreStages <= kQMetadataStages); for (int group = 0; group < num_groups; ++group) { int const q_stage = group % kQStages; int const q_phase = (group / kQStages) & 1; int const producer_phase = q_phase ^ 1; int const metadata_stage = group & (kQMetadataStages - 1); + bool const prefetch_boundary = (group % kQsplitPrefetchGroups) == 0; + // Every loader warp waits for the stage itself; no per-group warpgroup barrier. + cute::wait_barrier(storage.q_empty[q_stage], producer_phase); if (warp_idx == WarpSpecialization::kLoadWarp) { - cute::wait_barrier(storage.q_empty[q_stage], producer_phase); + if (prefetch_boundary) { + CUTLASS_PRAGMA_UNROLL + for (int pass = 0; pass < 2; ++pass) { + int const entry = pass * 32 + lane; + int const qi = group * kQueriesPerGroup + entry; + int packed_qsplit = 0; + if (qi < q_count) { + packed_qsplit = + arguments.qsplit_indices_ptr[head_kv * arguments.qsplit_stride + row_start + qi]; + } + storage.qsplit_indices[(group + entry / kQueriesPerGroup) & (kQMetadataStages - 1)] + [entry % kQueriesPerGroup] = packed_qsplit; + } + __syncwarp(); + } if (lane == 0) { cute::set_barrier_transaction_bytes(storage.q_full[q_stage], kQueriesPerGroup * kQHeadsPerKv * kHeadDim); } if (lane < kQueriesPerGroup) { - int const qi = group * kQueriesPerGroup + lane; - int packed_qsplit = 0; - if (qi < q_count) { - packed_qsplit = - arguments.qsplit_indices_ptr[head_kv * arguments.qsplit_stride + row_start + qi]; - } - storage.qsplit_indices[metadata_stage][lane] = packed_qsplit; cutlass::arch::ClusterBarrier::arrive(&storage.q_full[q_stage]); } } - load_barrier.arrive_and_wait(); + if (prefetch_boundary) { + // Publish the freshly prefetched indices to the other loader warps. + load_barrier.arrive_and_wait(); + } if (lane == 0) { CUTLASS_PRAGMA_UNROLL @@ -240,15 +260,18 @@ CUTLASS_DEVICE void issue_pv_group(Storage &storage, TiledMmaPV tiled_mma_pv, Ou tO.data() = storage.tmem_base + kTmemOutputOffset + score_stage * kTmemOutputStride; tP.data() = storage.tmem_base + score_stage * kTmemScoreStride + kTmemProbabilityOffset; + // The softmax publishes P in two halves of 64 keys (probability_early_full, then + // probability_full); the k-blocks covering the first half run before the second wait. + constexpr int kEarlyKBlocks = size<2>(tP) / 2; tiled_mma_pv.accumulate_ = UMMA::ScaleOut::Zero; CUTLASS_PRAGMA_UNROLL - for (int k_block = 0; k_block < 2; ++k_block) { + for (int k_block = 0; k_block < kEarlyKBlocks; ++k_block) { gemm(tiled_mma_pv, tP(_, _, k_block), tV(_, _, k_block, 0), tO); tiled_mma_pv.accumulate_ = UMMA::ScaleOut::One; } cute::wait_barrier(storage.probability_full[score_stage], score_phase); CUTLASS_PRAGMA_UNROLL - for (int k_block = 2; k_block < size<2>(tP); ++k_block) { + for (int k_block = kEarlyKBlocks; k_block < size<2>(tP); ++k_block) { gemm(tiled_mma_pv, tP(_, _, k_block), tV(_, _, k_block, 0), tO); } cutlass::arch::umma_arrive(&storage.output_full[score_stage]); @@ -410,8 +433,6 @@ CUTLASS_DEVICE void run_epilogue_warpgroup(Storage &storage, PrefillArguments co Tensor tO = partition_fragment_C(tiled_mma_pv, make_shape(Int<128>{}, Int<128>{})); Tensor cO = make_identity_tensor(make_shape(Int<128>{}, Int<128>{})); int const group_thread = tid - WarpSpecialization::kEpilogueWarp * 32; - cutlass::arch::NamedBarrier epilogue_barrier(WarpSpecialization::kEpilogueWarps * 32, - kEpilogueBarrierId); for (int group = 0; group < num_groups; ++group) { int const score_stage = group % kScoreStages; @@ -421,14 +442,17 @@ CUTLASS_DEVICE void run_epilogue_warpgroup(Storage &storage, PrefillArguments co cute::wait_barrier(storage.stats_full[score_stage], score_phase); Tensor tOCurrent = tO; tOCurrent.data() = storage.tmem_base + kTmemOutputOffset + score_stage * kTmemOutputStride; - store_partial_output(tiled_mma_pv, tOCurrent, cO, arguments.o_partial_ptr, - arguments.lse_partial_ptr, arguments.total_q, arguments.num_q_heads, - arguments.softmax_scale_log2, head_kv, q_count, q_batch_offset, group, - group_thread, storage.qsplit_indices[metadata_stage], - storage.row_sum[score_stage], storage.row_max[score_stage]); - epilogue_barrier.arrive_and_wait(); - cutlass::arch::ClusterBarrier::arrive(&storage.output_empty[score_stage]); - cutlass::arch::ClusterBarrier::arrive(&storage.stats_empty[score_stage]); + // output_empty and stats_empty expect one arrival per epilogue thread; store_partial_output + // arrives on each as soon as that thread no longer needs the stage (after its own TMEM-load + // fence for O), so no warpgroup barrier is needed and the MMA can refill the stage while + // this group's stores drain. + store_partial_output(tiled_mma_pv, tOCurrent, cO, &storage.output_empty[score_stage], + &storage.stats_empty[score_stage], arguments.o_partial_ptr, + arguments.o_partial_split_stride, arguments.lse_partial_ptr, + arguments.total_q, arguments.num_q_heads, arguments.softmax_scale_log2, + head_kv, q_count, q_batch_offset, group, group_thread, + storage.qsplit_indices[metadata_stage], storage.row_sum[score_stage], + storage.row_max[score_stage]); } cutlass::arch::NamedBarrier tmem_barrier(WarpSpecialization::kTmemParticipantWarps * 32, diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/nvfp4_to_e4m3.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/nvfp4_to_e4m3.cuh index 1afac17d..d5ad9ed4 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/nvfp4_to_e4m3.cuh +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/nvfp4_to_e4m3.cuh @@ -4,20 +4,85 @@ #include "cutlass/cutlass.h" -#if !defined(__CUDACC_VER_MAJOR__) || \ - (__CUDACC_VER_MAJOR__ < 13) || \ - (__CUDACC_VER_MAJOR__ == 13 && __CUDACC_VER_MINOR__ < 4) +#if !defined(MINIMAX_MSA_Q8KV4_HAS_QMUL4) +#error "The Q8KV4 prefill JIT must define MINIMAX_MSA_Q8KV4_HAS_QMUL4" +#endif + +#if MINIMAX_MSA_Q8KV4_HAS_QMUL4 && \ + (!defined(__CUDACC_VER_MAJOR__) || (__CUDACC_VER_MAJOR__ < 13) || \ + (__CUDACC_VER_MAJOR__ == 13 && __CUDACC_VER_MINOR__ < 4)) #error "Q8KV4 prefill attention QMUL4 requires CUDA Toolkit 13.4 or newer" #endif namespace minimax::msa_v1::attention::prefill::q8kv4::sm100::common { -CUTLASS_DEVICE void nvfp4_to_e4m3x4( - uint32_t& output, uint16_t packed_fp4, uint32_t scale_e4m3x4) { - asm volatile( - "mul.rn.satfinite.e4m3x4.e2m1x4.e4m3x4 %0, %1, %2;" - : "=r"(output) - : "h"(packed_fp4), "r"(scale_e4m3x4)); +// Dequantizes eight consecutive E2M1 values (one 32-bit word, element i in nibble i) that +// share one E4M3 scale into eight E4M3 values: `output_lo` holds elements 0-3 and +// `output_hi` elements 4-7, each byte i being element i. `scale_word` comes from +// `make_dequant_scale_word` so the per-element scale broadcast happens once per group. + +#if MINIMAX_MSA_Q8KV4_HAS_QMUL4 + +CUTLASS_DEVICE uint32_t make_dequant_scale_word(uint8_t scale_e4m3) { + return static_cast(scale_e4m3) * 0x01010101u; +} + +CUTLASS_DEVICE void nvfp4_to_e4m3x4(uint32_t &output, uint16_t packed_fp4, uint32_t scale_e4m3x4) { + asm volatile("mul.rn.satfinite.e4m3x4.e2m1x4.e4m3x4 %0, %1, %2;" + : "=r"(output) + : "h"(packed_fp4), "r"(scale_e4m3x4)); +} + +CUTLASS_DEVICE void dequant_e2m1x8_uniform_scale(uint32_t &output_lo, uint32_t &output_hi, + uint32_t packed_fp4, uint32_t scale_word) { + nvfp4_to_e4m3x4(output_lo, static_cast(packed_fp4), scale_word); + nvfp4_to_e4m3x4(output_hi, static_cast(packed_fp4 >> 16), scale_word); } -} // namespace minimax::msa_v1::attention::prefill::q8kv4::sm100::common +#else + +// Architectures without QMUL4 (SM107) multiply in packed FP16. An E2M1 x E4M3 +// product has at most five significant bits and stays within the FP16 normal +// range, so the FP16 product is exact and the single rounding happens in the +// final E4M3 conversion, exactly as in QMUL4. +CUTLASS_DEVICE uint32_t make_dequant_scale_word(uint8_t scale_e4m3) { + uint32_t scale_f16x2; + asm("{\n" + ".reg .b16 scale_pair;\n" + "mov.b16 scale_pair, %1;\n" + "cvt.rn.f16x2.e4m3x2 %0, scale_pair;\n" + "}\n" + : "=r"(scale_f16x2) + : "h"(static_cast(scale_e4m3 * 0x0101u))); + return scale_f16x2; +} + +CUTLASS_DEVICE void dequant_e2m1x8_uniform_scale(uint32_t &output_lo, uint32_t &output_hi, + uint32_t packed_fp4, uint32_t scale_f16x2) { + asm volatile("{\n" + ".reg .b8 e0, e1, e2, e3;\n" + ".reg .b32 f0, f1, f2, f3;\n" + ".reg .b16 q0, q1, q2, q3;\n" + "mov.b32 {e0, e1, e2, e3}, %2;\n" + "cvt.rn.f16x2.e2m1x2 f0, e0;\n" + "cvt.rn.f16x2.e2m1x2 f1, e1;\n" + "cvt.rn.f16x2.e2m1x2 f2, e2;\n" + "cvt.rn.f16x2.e2m1x2 f3, e3;\n" + "mul.rn.f16x2 f0, f0, %3;\n" + "mul.rn.f16x2 f1, f1, %3;\n" + "mul.rn.f16x2 f2, f2, %3;\n" + "mul.rn.f16x2 f3, f3, %3;\n" + "cvt.rn.satfinite.e4m3x2.f16x2 q0, f0;\n" + "cvt.rn.satfinite.e4m3x2.f16x2 q1, f1;\n" + "cvt.rn.satfinite.e4m3x2.f16x2 q2, f2;\n" + "cvt.rn.satfinite.e4m3x2.f16x2 q3, f3;\n" + "mov.b32 %0, {q0, q1};\n" + "mov.b32 %1, {q2, q3};\n" + "}\n" + : "=&r"(output_lo), "=&r"(output_hi) + : "r"(packed_fp4), "r"(scale_f16x2)); +} + +#endif + +} // namespace minimax::msa_v1::attention::prefill::q8kv4::sm100::common diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_config.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_config.cuh index 812fce14..44c9e418 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_config.cuh +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_config.cuh @@ -5,6 +5,12 @@ #include "cutlass/cutlass.h" #include "cutlass/float8.h" +// Defined by the JIT for the host and device passes alike (the cute arch macros are device-only), +// so the kernel instantiation the host registers is the one the cubin holds. +#if !defined(MINIMAX_MSA_PREFILL_Q8KV4_SM107) +#error "The Q8KV4 prefill JIT must define MINIMAX_MSA_PREFILL_Q8KV4_SM107" +#endif + namespace minimax::msa_v1::attention::prefill::q8kv4::detail { using Element = cutlass::float_e4m3_t; @@ -14,15 +20,15 @@ inline constexpr int kQHeadsPerKv = 16; inline constexpr int kHeadDim = 128; inline constexpr int kPageSize = 128; inline constexpr int kQueriesPerGroup = 128 / kQHeadsPerKv; -inline constexpr int kQStages = 3; +inline constexpr int kQStages = 8; inline constexpr int kScoreStages = 2; -inline constexpr int kQMetadataStages = 16; +inline constexpr int kQMetadataStages = 32; inline constexpr int kTmemScoreOffset = 0; inline constexpr int kTmemScoreStride = 128; -inline constexpr int kTmemProbabilityOffset = 96; inline constexpr int kTmemOutputOffset = 256; inline constexpr int kTmemOutputStride = 128; +inline constexpr int kTmemProbabilityOffset = 96; inline constexpr int kTmemColumns = 512; inline constexpr int kPackedKvBytes = kPageSize * kHeadDim / 2; @@ -102,7 +108,6 @@ inline constexpr int kOtherRegisters = 64; static_assert(kSoftmax0Registers + kSoftmax1Registers + kEpilogueRegisters + kOtherRegisters <= 512); -inline constexpr int kEpilogueBarrierId = 4; inline constexpr int kKvDequantKBarrierId = 6; inline constexpr int kKvDequantVBarrierId = 7; inline constexpr int kTmemBarrierId = 0; diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_math.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_math.cuh index 09afa045..2cbedf46 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_math.cuh +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/prefill_attention_math.cuh @@ -5,6 +5,7 @@ #include #include +#include #include #include "cute/arch/copy_sm100.hpp" @@ -37,49 +38,40 @@ CUTLASS_DEVICE int real_col_to_stg128_half_fake_col(int col) { return tile * 32 + lane * 8 + group * 2 + element; } +// Pure functions of their operands: plain (non-volatile) asm lets ptxas schedule the exp loop's +// independent chains across each other instead of in program order. CUTLASS_DEVICE float rcp_approx_ftz(float value) { float result; - asm volatile("rcp.approx.ftz.f32 %0, %1;" : "=f"(result) : "f"(value)); + asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(result) : "f"(value)); return result; } CUTLASS_DEVICE float exp2_approx_ftz(float value) { float result; - asm volatile("ex2.approx.ftz.f32 %0, %1;" : "=f"(result) : "f"(value)); + asm("ex2.approx.ftz.f32 %0, %1;" : "=f"(result) : "f"(value)); return result; } CUTLASS_DEVICE float log2_approx_ftz(float value) { float result; - asm volatile("lg2.approx.ftz.f32 %0, %1;" : "=f"(result) : "f"(value)); + asm("lg2.approx.ftz.f32 %0, %1;" : "=f"(result) : "f"(value)); return result; } CUTLASS_DEVICE float2 add_packed_f32x2(float2 lhs, float2 rhs) { float2 result; - asm volatile("add.rn.ftz.f32x2 %0, %1, %2;" - : "=l"(reinterpret_cast(result)) - : "l"(reinterpret_cast(lhs)), - "l"(reinterpret_cast(rhs))); - return result; -} - -CUTLASS_DEVICE float2 mul_packed_f32x2(float2 lhs, float2 rhs) { - float2 result; - asm volatile("mul.rn.ftz.f32x2 %0, %1, %2;" - : "=l"(reinterpret_cast(result)) - : "l"(reinterpret_cast(lhs)), - "l"(reinterpret_cast(rhs))); + asm("add.rn.ftz.f32x2 %0, %1, %2;" + : "=l"(reinterpret_cast(result)) + : "l"(reinterpret_cast(lhs)), "l"(reinterpret_cast(rhs))); return result; } CUTLASS_DEVICE float2 fma_packed_f32x2(float2 lhs, float2 rhs, float2 addend) { float2 result; - asm volatile("fma.rn.ftz.f32x2 %0, %1, %2, %3;" - : "=l"(reinterpret_cast(result)) - : "l"(reinterpret_cast(lhs)), - "l"(reinterpret_cast(rhs)), - "l"(reinterpret_cast(addend))); + asm("fma.rn.ftz.f32x2 %0, %1, %2, %3;" + : "=l"(reinterpret_cast(result)) + : "l"(reinterpret_cast(lhs)), "l"(reinterpret_cast(rhs)), + "l"(reinterpret_cast(addend))); return result; } @@ -108,32 +100,6 @@ template CUTLASS_DEVICE auto make_16x256b_tensor_mn_view(Tensor t return make_tensor(tensor.data(), composition(converted_sm90, converted_mn)); } -CUTLASS_DEVICE void store_bf16x8_cs(cutlass::bfloat16_t *destination, float value0, float value1, - float value2, float value3, float value4, float value5, - float value6, float value7) { - asm volatile("{\n" - ".reg .b16 h0, h1, h2, h3, h4, h5, h6, h7;\n" - ".reg .b32 p0, p1, p2, p3;\n" - "cvt.rn.bf16.f32 h0, %1;\n" - "cvt.rn.bf16.f32 h1, %2;\n" - "cvt.rn.bf16.f32 h2, %3;\n" - "cvt.rn.bf16.f32 h3, %4;\n" - "cvt.rn.bf16.f32 h4, %5;\n" - "cvt.rn.bf16.f32 h5, %6;\n" - "cvt.rn.bf16.f32 h6, %7;\n" - "cvt.rn.bf16.f32 h7, %8;\n" - "mov.b32 p0, {h0, h1};\n" - "mov.b32 p1, {h2, h3};\n" - "mov.b32 p2, {h4, h5};\n" - "mov.b32 p3, {h6, h7};\n" - "st.global.cs.v4.b32 [%0], {p0, p1, p2, p3};\n" - "}\n" - : - : "l"(destination), "f"(value0), "f"(value1), "f"(value2), "f"(value3), "f"(value4), - "f"(value5), "f"(value6), "f"(value7) - : "memory"); -} - template CUTLASS_DEVICE void tmem_store_16_impl(Tensor const &source, uint32_t destination, cute::index_sequence) { @@ -180,16 +146,29 @@ CUTLASS_DEVICE void softmax_to_tmem(TiledMmaQK tiled_mma_qk, uint32_t score_addr float maximum1 = -INFINITY; float maximum2 = -INFINITY; float maximum3 = -INFINITY; - CUTLASS_PRAGMA_UNROLL - for (int col = 0; col < 128; col += 8) { + // Only the query's own page is partially visible; history pages (the common case) are read in + // full, so the per-element select is skipped when every row of the warp sees all 128 keys. The + // test is warp-uniform by construction (all lanes vote), so both paths are warp-uniform. + if (__all_sync(0xffffffffu, visible_cols >= 128)) { + CUTLASS_PRAGMA_UNROLL + for (int col = 0; col < 128; col += 8) { + maximum0 = fmaxf(maximum0, fmaxf(rS(col), rS(col + 1))); + maximum1 = fmaxf(maximum1, fmaxf(rS(col + 2), rS(col + 3))); + maximum2 = fmaxf(maximum2, fmaxf(rS(col + 4), rS(col + 5))); + maximum3 = fmaxf(maximum3, fmaxf(rS(col + 6), rS(col + 7))); + } + } else { CUTLASS_PRAGMA_UNROLL - for (int value = 0; value < 8; ++value) { - rS(col + value) = col + value < visible_cols ? rS(col + value) : -INFINITY; + for (int col = 0; col < 128; col += 8) { + CUTLASS_PRAGMA_UNROLL + for (int value = 0; value < 8; ++value) { + rS(col + value) = col + value < visible_cols ? rS(col + value) : -INFINITY; + } + maximum0 = fmaxf(maximum0, fmaxf(rS(col), rS(col + 1))); + maximum1 = fmaxf(maximum1, fmaxf(rS(col + 2), rS(col + 3))); + maximum2 = fmaxf(maximum2, fmaxf(rS(col + 4), rS(col + 5))); + maximum3 = fmaxf(maximum3, fmaxf(rS(col + 6), rS(col + 7))); } - maximum0 = fmaxf(maximum0, fmaxf(rS(col), rS(col + 1))); - maximum1 = fmaxf(maximum1, fmaxf(rS(col + 2), rS(col + 3))); - maximum2 = fmaxf(maximum2, fmaxf(rS(col + 4), rS(col + 5))); - maximum3 = fmaxf(maximum3, fmaxf(rS(col + 6), rS(col + 7))); } float const maximum = fmaxf(fmaxf(maximum0, maximum1), fmaxf(maximum2, maximum3)); @@ -272,19 +251,16 @@ CUTLASS_DEVICE void softmax_to_tmem(TiledMmaQK tiled_mma_qk, uint32_t score_addr row_max = maximum; } +// Thread-level views of one 64-column half of the O accumulator: the tiled TMEM copy, its source +// partition and the matching coordinate partition. template -CUTLASS_DEVICE void -store_partial_output_pass(TiledMmaPV tiled_mma_pv, OutputTensor tO, CoordinateTensor cO, - cutlass::bfloat16_t *o_partial_ptr, int total_q, int num_q_heads, - int head_kv, int q_count, int q_batch_offset, int group, int group_thread, - int output_token_base, int output_qsplit0, int output_qsplit1, - float const *row_sum) { +CUTLASS_DEVICE auto partial_output_pass_views(TiledMmaPV tiled_mma_pv, OutputTensor tO, + CoordinateTensor cO, int group_thread) { + constexpr int kColumnPassSize = 64; auto thr_mma = tiled_mma_pv.get_slice(0); Tensor tOcO = thr_mma.partition_C(cO); - constexpr int kColumnPassSize = 64; Tensor tOcOPass = logical_divide(tOcO, make_layout(make_shape(Int<128>{}, Int{}))); - Tensor tOPass = tO; tOPass.data() = tO.data() + ColumnPass * kColumnPassSize; Tensor tOPassDivided = @@ -294,73 +270,65 @@ store_partial_output_pass(TiledMmaPV tiled_mma_pv, OutputTensor tO, CoordinateTe auto thread_tmem_load = tiled_tmem_load.get_slice(group_thread); Tensor tTMEMtOAll = thread_tmem_load.partition_S(tOPassDivided(make_coord(_, _), _)); Tensor tTMEMcOAll = thread_tmem_load.partition_D(tOcOPass(make_coord(_, _), _)); - Tensor tTMEMtOPass = tTMEMtOAll(_, _, _, _0{}); - Tensor tTMEMcOPass = tTMEMcOAll(_, _, _, _0{}); - Tensor rOPass = make_tensor(shape(tTMEMcOPass)); - copy(tiled_tmem_load, tTMEMtOPass, rOPass); - cutlass::arch::fence_view_async_tmem_load(); + return cute::make_tuple(tiled_tmem_load, tTMEMtOAll(_, _, _, _0{}), tTMEMcOAll(_, _, _, _0{})); +} +// Per-thread view of the O accumulator: the 16dp256b TMEM load gives each thread, per 64-column +// pass, two "row indices" x four 8-value chunks that cover four accumulator rows (A, A+8, A+16, +// A+24 for A = 32 * warp + lane / 4) x two column offsets (c, c+32). A row is one (token, head) +// of the group, so its output pointer, scale and validity are computed once per group and reused +// by the four 16-byte chunks the thread stores for it (two per pass). Plain C++ arithmetic keeps +// the compiler free to interleave the rows and column groups; the rounding (rcp.approx, fp32 +// multiply, round-to-nearest bf16) is unchanged. +struct PartialRowState { + cutlass::bfloat16_t *ptr; + float scale; + bool valid; +}; + +template +CUTLASS_DEVICE void store_partial_output_pass(RegTensor const &rOPass, + CoordinateTensor const &tTMEMcOPass, + PartialRowState const (&rows)[2][2]) { + constexpr int kColumnPassSize = 64; Tensor rOMnFull = make_16x256b_tensor_mn_view(rOPass); Tensor cOMnFull = make_16x256b_tensor_mn_view(tTMEMcOPass); Tensor rOMn = rOMnFull(_, _, _0{}); Tensor cOMn = cOMnFull(_, _, _0{}); - static_assert(rank(rOMn) == 2); - static_assert(size<0>(rOMn) == 2); - static_assert(size<1>(rOMn) == 32); - static_assert(rank(cOMn) == 2); - static_assert(size<0>(cOMn) == 2); - static_assert(size<1>(cOMn) == 32); + static_assert(rank(rOMn) == 2 && size<0>(rOMn) == 2 && size<1>(rOMn) == 32); CUTLASS_PRAGMA_UNROLL - for (int row_index = 0; row_index < size<0>(rOMn); ++row_index) { + for (int row_index = 0; row_index < 2; ++row_index) { CUTLASS_PRAGMA_UNROLL - for (int column_group = 0; column_group < size<1>(rOMn) / 8; ++column_group) { + for (int column_group = 0; column_group < 4; ++column_group) { int const column_base = column_group * 8; - int const row = get<0>(cOMn(row_index, column_base)); - int const token = row / kQHeadsPerKv; - int const qi = group * kQueriesPerGroup + token; - if (qi < q_count) { - int const packed_qsplit = token == output_token_base ? output_qsplit0 : output_qsplit1; - int const q_idx = decode_q_idx(packed_qsplit); - int const split = decode_split_idx(packed_qsplit); - int const q_abs = q_batch_offset + q_idx; - int const head = head_kv * kQHeadsPerKv + row % kQHeadsPerKv; - float const sum = row_sum[row]; - float const scale = sum > 0.0f ? rcp_approx_ftz(sum) : 0.0f; - float2 const packed_scale = make_float2(scale, scale); - float2 const output0 = mul_packed_f32x2( - make_float2(rOMn(row_index, column_base), rOMn(row_index, column_base + 1)), - packed_scale); - float2 const output1 = mul_packed_f32x2( - make_float2(rOMn(row_index, column_base + 2), rOMn(row_index, column_base + 3)), - packed_scale); - float2 const output2 = mul_packed_f32x2( - make_float2(rOMn(row_index, column_base + 4), rOMn(row_index, column_base + 5)), - packed_scale); - float2 const output3 = mul_packed_f32x2( - make_float2(rOMn(row_index, column_base + 6), rOMn(row_index, column_base + 7)), - packed_scale); - int const col = get<1>(cOMn(row_index, column_base)) + ColumnPass * kColumnPassSize; - int const fake_col = real_col_to_stg128_half_fake_col(col); - int64_t const output_offset = - ((static_cast(split) * total_q + q_abs) * num_q_heads + head) * kHeadDim + - fake_col; - store_bf16x8_cs(o_partial_ptr + output_offset, output0.x, output0.y, output1.x, output1.y, - output2.x, output2.y, output3.x, output3.y); + PartialRowState const &state = rows[row_index][column_group / 2]; + int const col = get<1>(cOMn(row_index, column_base)) + ColumnPass * kColumnPassSize; + int const fake_col = real_col_to_stg128_half_fake_col(col); + uint32_t packed[4]; + CUTLASS_PRAGMA_UNROLL + for (int pair = 0; pair < 4; ++pair) { + float2 const value = make_float2(rOMn(row_index, column_base + 2 * pair) * state.scale, + rOMn(row_index, column_base + 2 * pair + 1) * state.scale); + __nv_bfloat162 const bf16_pair = __float22bfloat162_rn(value); + packed[pair] = *reinterpret_cast(&bf16_pair); + } + if (state.valid) { + __stcs(reinterpret_cast(state.ptr + fake_col), + make_uint4(packed[0], packed[1], packed[2], packed[3])); } } } - - cutlass::arch::fence_view_async_tmem_load(); } template CUTLASS_DEVICE void store_partial_output(TiledMmaPV tiled_mma_pv, OutputTensor tO, CoordinateTensor cO, - cutlass::bfloat16_t *o_partial_ptr, float *lse_partial_ptr, int total_q, - int num_q_heads, float softmax_scale_log2, int head_kv, int q_count, - int q_batch_offset, int group, int group_thread, int const *qsplit_indices, - float const *row_sum, float const *row_max) { + uint64_t *output_empty, uint64_t *stats_empty, + cutlass::bfloat16_t *o_partial_ptr, int64_t o_partial_split_stride, + float *lse_partial_ptr, int total_q, int num_q_heads, float softmax_scale_log2, + int head_kv, int q_count, int q_batch_offset, int group, int group_thread, + int const *qsplit_indices, float const *row_sum, float const *row_max) { int const lane = group_thread & 31; int const output_token_base = (group_thread / 32) * 2; int output_qsplit0 = 0; @@ -372,13 +340,55 @@ store_partial_output(TiledMmaPV tiled_mma_pv, OutputTensor tO, CoordinateTensor output_qsplit0 = __shfl_sync(0xffffffffu, output_qsplit0, 0); output_qsplit1 = __shfl_sync(0xffffffffu, output_qsplit1, 0); - store_partial_output_pass<0>(tiled_mma_pv, tO, cO, o_partial_ptr, total_q, num_q_heads, head_kv, - q_count, q_batch_offset, group, group_thread, output_token_base, - output_qsplit0, output_qsplit1, row_sum); - store_partial_output_pass<1>(tiled_mma_pv, tO, cO, o_partial_ptr, total_q, num_q_heads, head_kv, - q_count, q_batch_offset, group, group_thread, output_token_base, - output_qsplit0, output_qsplit1, row_sum); - cutlass::arch::fence_view_async_tmem_load(); + auto views0 = partial_output_pass_views<0>(tiled_mma_pv, tO, cO, group_thread); + auto views1 = partial_output_pass_views<1>(tiled_mma_pv, tO, cO, group_thread); + + // The four rows this thread stores (see store_partial_output_pass): rows[row_index][half] + // is the row of column groups 2 * half and 2 * half + 1 of that row index. This thread's LSE + // row stats are read here too, before the stats stage is handed back to the softmax. + Tensor cOMn = make_16x256b_tensor_mn_view(get<2>(views0))(_, _, _0{}); + float const lse_sum = row_sum[group_thread]; + float const lse_max = row_max[group_thread]; + PartialRowState rows[2][2]; + CUTLASS_PRAGMA_UNROLL + for (int row_index = 0; row_index < 2; ++row_index) { + CUTLASS_PRAGMA_UNROLL + for (int half = 0; half < 2; ++half) { + int const row = get<0>(cOMn(row_index, half * 16)); + int const token = row / kQHeadsPerKv; + int const qi = group * kQueriesPerGroup + token; + int const packed_qsplit = token == output_token_base ? output_qsplit0 : output_qsplit1; + int const q_idx = decode_q_idx(packed_qsplit); + int const split = decode_split_idx(packed_qsplit); + int const q_abs = q_batch_offset + q_idx; + int const head = head_kv * kQHeadsPerKv + row % kQHeadsPerKv; + int64_t const row_offset = static_cast(split) * o_partial_split_stride + + (static_cast(q_abs) * num_q_heads + head) * kHeadDim; + float const sum = row_sum[row]; + rows[row_index][half].ptr = o_partial_ptr + row_offset; + rows[row_index][half].scale = sum > 0.0f ? rcp_approx_ftz(sum) : 0.0f; + rows[row_index][half].valid = qi < q_count; + } + } + // Every stat this thread needs is in registers: the softmax may publish the next group's. + cutlass::arch::ClusterBarrier::arrive(stats_empty); + + // One 64-column half at a time: the epilogue register budget (96) holds one half's 32 + // accumulators plus the row state, not both halves. The O stage is handed back to the MMA as + // soon as its second half is in registers, before this group's stores drain. + { + Tensor rO0 = make_tensor(shape(get<2>(views0))); + copy(get<0>(views0), get<1>(views0), rO0); + cutlass::arch::fence_view_async_tmem_load(); + store_partial_output_pass<0>(rO0, get<2>(views0), rows); + } + { + Tensor rO1 = make_tensor(shape(get<2>(views1))); + copy(get<0>(views1), get<1>(views1), rO1); + cutlass::arch::fence_view_async_tmem_load(); + cutlass::arch::ClusterBarrier::arrive(output_empty); + store_partial_output_pass<1>(rO1, get<2>(views1), rows); + } int const row = group_thread; int const token = row / kQHeadsPerKv; @@ -388,15 +398,15 @@ store_partial_output(TiledMmaPV tiled_mma_pv, OutputTensor tO, CoordinateTensor int const q_idx = decode_q_idx(packed_qsplit); int const split = decode_split_idx(packed_qsplit); int const q_abs = q_batch_offset + q_idx; - int const head = head_kv * kQHeadsPerKv + row % kQHeadsPerKv; - float const sum = row_sum[row]; + int const lse_head = head_kv * kQHeadsPerKv + row % kQHeadsPerKv; float lse = -INFINITY; - if (sum > 0.0f && isfinite(row_max[row])) { + if (lse_sum > 0.0f && isfinite(lse_max)) { constexpr float kLn2 = 0.6931471805599453f; - lse = (row_max[row] * softmax_scale_log2 + log2_approx_ftz(sum) - kLog2Fp8ProbabilityScale) * + lse = (lse_max * softmax_scale_log2 + log2_approx_ftz(lse_sum) - kLog2Fp8ProbabilityScale) * kLn2; } - int64_t const lse_offset = (static_cast(split) * total_q + q_abs) * num_q_heads + head; + int64_t const lse_offset = + (static_cast(split) * total_q + q_abs) * num_q_heads + lse_head; lse_partial_ptr[lse_offset] = lse; } } diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/sm107_mma_ts.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/sm107_mma_ts.cuh new file mode 100644 index 00000000..9a8b2da0 --- /dev/null +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/common/sm107_mma_ts.cuh @@ -0,0 +1,112 @@ +#pragma once + +// tcgen05 kind::f8f6f4 MMA with A in TMEM and K = 64 for SM107. CUTLASS 4.8 provides the SS form +// (SM107_MMA_F8F6F4_SS) but no TS form; the instruction is the same as SM100's TS form, only the +// instruction descriptor selects the 64-deep K (make_sm107_instr_desc), which runs at twice the +// SM100 FP8 rate on SM107. + +#include "cute/tensor.hpp" + +#include "sm100/common/prefill_attention_config.cuh" + +#if MINIMAX_MSA_PREFILL_Q8KV4_SM107 + +#include "cute/arch/config.hpp" +#include "cute/arch/mma_sm100_desc.hpp" +#include "cute/arch/mma_sm100_umma.hpp" +#include "cute/atom/mma_traits.hpp" +#include "cute/atom/mma_traits_sm100.hpp" + +namespace minimax::msa_v1::attention::prefill::q8kv4::detail { + +template +struct Sm107MmaF8F6F4Ts { + static_assert(M == 128, "Sm107MmaF8F6F4Ts: M must be 128"); + static_assert(N % 16 == 0 && N >= 16 && N <= 256, "Sm107MmaF8F6F4Ts: N must be a multiple of 16"); + static_assert(a_major == cute::UMMA::Major::K, "Sm107MmaF8F6F4Ts: A from TMEM is K-major"); + + using DRegisters = void; + using ARegisters = uint32_t[1]; + using BRegisters = uint64_t[1]; + using CRegisters = uint32_t[1]; + + CUTE_HOST_DEVICE static void fma(uint32_t const &tmem_a, uint64_t const &desc_b, + uint32_t const &tmem_c, uint32_t const &scaleC, + uint64_t const &idescE) { +#if defined(CUTE_ARCH_TCGEN05_RUBIN_F8F6F4_MMA_ENABLED) + if (cute::elect_one_sync()) { + uint32_t mask[4] = {0, 0, 0, 0}; + asm volatile("{\n\t" + ".reg .pred p;\n\t" + "setp.ne.b32 p, %4, 0;\n\t" + "tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], [%1], %2, %3, " + "{%5, %6, %7, %8}, p; \n\t" + "}\n" + : + : "r"(tmem_c), "r"(tmem_a), "l"(desc_b), "r"(uint32_t(idescE >> 32)), + "r"(scaleC), "r"(mask[0]), "r"(mask[1]), "r"(mask[2]), "r"(mask[3])); + } +#else + CUTE_INVALID_CONTROL_PATH( + "Sm107MmaF8F6F4Ts requires CUTE_ARCH_TCGEN05_RUBIN_F8F6F4_MMA_ENABLED"); +#endif + } +}; + +} // namespace minimax::msa_v1::attention::prefill::q8kv4::detail + +namespace cute { + +template +struct MMA_Traits> { + using ValTypeD = c_type; + using ValTypeA = a_type; + using ValTypeB = b_type; + using ValTypeC = c_type; + static_assert(cute::sizeof_bits_v <= 8 && cute::sizeof_bits_v <= 8); + + using FrgTypeA = UMMA::tmem_frg_1sm; + using FrgTypeB = UMMA::smem_desc; + using FrgTypeC = UMMA::tmem_frg_1sm; + + // SM107: 512-bit logical K per instruction, 64 elements of 8 bits. + static constexpr int K = 64; + + using Shape_MNK = Shape, Int, Int>; + using ThrID = Layout<_1>; + using ALayout = Layout, Int>>, Stride<_0, Stride<_1, Int>>>; + using BLayout = Layout, Int>>, Stride<_0, Stride<_1, Int>>>; + using CLayout = Layout, Int>>, Stride<_0, Stride<_1, Int>>>; + + UMMA::ScaleOut accumulate_ = UMMA::ScaleOut::One; + + UMMA::InstrDescriptor idesc_ = UMMA::make_sm107_instr_desc(); + + template + CUTE_HOST_DEVICE constexpr friend void + mma_unpack(MMA_Traits const &traits, Tensor &D, Tensor const &A, + Tensor const &B, Tensor const &C) { + static_assert(is_tmem::value, "Expected tmem in MMA_Atom::call"); + static_assert(is_tmem::value, "Expected tmem in MMA_Atom::call"); + static_assert(is_rmem::value, "Expected desc registers in MMA_Atom::call"); + static_assert(is_tmem::value, "Expected tmem in MMA_Atom::call"); + uint64_t tmem_a = raw_pointer_cast(A.data()); + uint64_t desc_b = B[0]; + uint32_t tmem_c = raw_pointer_cast(D.data()); + uint64_t idesc = UMMA::make_runtime_instr_desc<>(traits.idesc_); + minimax::msa_v1::attention::prefill::q8kv4::detail:: + Sm107MmaF8F6F4Ts::fma( + tmem_a, desc_b, tmem_c, uint32_t(traits.accumulate_), idesc); + } +}; + +} // namespace cute + +#endif // MINIMAX_MSA_PREFILL_Q8KV4_SM107 diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention.hpp b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention.hpp index 04b328c4..04aee3af 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention.hpp +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention.hpp @@ -22,7 +22,14 @@ struct PrefillArguments { int32_t const *scheduler_metadata_ptr = nullptr; int32_t const *work_count_ptr = nullptr; cutlass::bfloat16_t *o_partial_ptr = nullptr; + // Elements between consecutive split slabs of o_partial: total_q * num_q_heads * 128 for a + // contiguous buffer, more when the slabs are padded (locality-domain striping). + int64_t o_partial_split_stride = 0; float *lse_partial_ptr = nullptr; + // Optional int32 counters the combine claims its tiles from; this kernel zeroes them for the + // combine that follows it in the stream (the previous combine has completed when it starts). + int32_t *combine_tile_counters_ptr = nullptr; + int combine_tile_counter_count = 0; int total_q = 0; int num_q_heads = 0; diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention_launch.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention_launch.cuh index 29eb109e..e5354c5f 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention_launch.cuh +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/device/prefill_attention_launch.cuh @@ -1,5 +1,6 @@ #pragma once +#include "sm100/common/sm107_mma_ts.cuh" #include "sm100/kernel/sm100_prefill_attention_kernel.cuh" #include @@ -8,6 +9,10 @@ #include #include "cute/tensor.hpp" +#if MINIMAX_MSA_PREFILL_Q8KV4_SM107 +#include "cute/arch/mma_sm107_umma.hpp" +#include "cute/atom/mma_traits_sm107.hpp" +#endif #include "cutlass/gemm/collective/builders/sm100_common.inl" namespace minimax::msa_v1::attention::prefill::q8kv4 { @@ -66,12 +71,20 @@ cudaError_t launch_prefill_attention(PrefillArguments const &arguments, cudaStre using namespace cute; using namespace detail; - using TiledMmaQK = - decltype(make_tiled_mma(SM100_MMA_F8F6F4_SS{})); - using TiledMmaPV = - decltype(make_tiled_mma(SM100_MMA_F8F6F4_TS{})); +#if MINIMAX_MSA_PREFILL_Q8KV4_SM107 + // SM107: K = 64 per instruction, twice the SM100 FP8 rate. + using QkMmaAtom = + SM107_MMA_F8F6F4_SS; + using PvMmaAtom = detail::Sm107MmaF8F6F4Ts; +#else + using QkMmaAtom = + SM100_MMA_F8F6F4_SS; + using PvMmaAtom = + SM100_MMA_F8F6F4_TS; +#endif + using TiledMmaQK = decltype(make_tiled_mma(QkMmaAtom{})); + using TiledMmaPV = decltype(make_tiled_mma(PvMmaAtom{})); using QShape = decltype(make_shape(Int<128>{}, Int<128>{}, Int{})); using KShape = decltype(make_shape(Int<128>{}, Int<128>{}, _1{})); diff --git a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/kernel/sm100_prefill_attention_kernel.cuh b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/kernel/sm100_prefill_attention_kernel.cuh index b9949a58..3f57ab15 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/kernel/sm100_prefill_attention_kernel.cuh +++ b/inference/msa_v1/attention/prefill/q8kv4/csrc/include/sm100/kernel/sm100_prefill_attention_kernel.cuh @@ -10,25 +10,32 @@ namespace minimax::msa_v1::attention::prefill::q8kv4::detail { // 8-11: partial-output epilogue // 12: UMMA issuer and TMEM owner // 13-15: Q producers; warps 13 and 14 also issue K and V TMA -template -__global__ __launch_bounds__(WarpSpecialization::kThreads, 1) -void prefill_attention_kernel( +template +__global__ __launch_bounds__(WarpSpecialization::kThreads, 1) void prefill_attention_kernel( __grid_constant__ const KernelParams params) { - PrefillArguments const& arguments = params.arguments; + PrefillArguments const &arguments = params.arguments; // PDL may start this kernel before the schedule producer has published its metadata. cutlass::arch::wait_on_dependent_grids(); TiledMmaQK tiled_mma_qk; TiledMmaPV tiled_mma_pv; extern __shared__ char shared_memory[]; - Storage& storage = *reinterpret_cast(shared_memory); + Storage &storage = *reinterpret_cast(shared_memory); int const tid = static_cast(threadIdx.x); int const warp_idx = tid / 32; int const lane = tid % 32; - bool const active = - static_cast(blockIdx.x) < arguments.work_count_ptr[0]; + // The combine that follows this grid claims its tiles from these counters; the previous + // combine has completed (the wait above), so they are free to reset, whether or not this + // grid has any work. + if (blockIdx.x == 0 && tid == 0 && arguments.combine_tile_counters_ptr != nullptr) { + for (int i = 0; i < arguments.combine_tile_counter_count; ++i) { + arguments.combine_tile_counters_ptr[i] = 0; + } + __threadfence(); + } + + bool const active = static_cast(blockIdx.x) < arguments.work_count_ptr[0]; if (!active) { if (WarpSpecialization::is_mma_warp(warp_idx)) { cute::TMEM::Allocator1Sm allocator; @@ -49,8 +56,8 @@ void prefill_attention_kernel( cutlass::arch::fence_barrier_init(); __syncthreads(); - cutlass::arch::NamedBarrier tmem_barrier( - WarpSpecialization::kTmemParticipantWarps * 32, kTmemBarrierId); + cutlass::arch::NamedBarrier tmem_barrier(WarpSpecialization::kTmemParticipantWarps * 32, + kTmemBarrierId); if (WarpSpecialization::is_mma_warp(warp_idx)) { cute::TMEM::Allocator1Sm allocator; allocator.allocate(kTmemColumns, &storage.tmem_base); @@ -65,13 +72,11 @@ void prefill_attention_kernel( return; } if (WarpSpecialization::is_mma_warp(warp_idx)) { - run_mma_warp( - storage, tiled_mma_qk, tiled_mma_pv); + run_mma_warp(storage, tiled_mma_qk, tiled_mma_pv); return; } if (WarpSpecialization::is_softmax_warp(warp_idx)) { - run_softmax_warpgroup( - storage, arguments, tiled_mma_qk, warp_idx, tid); + run_softmax_warpgroup(storage, arguments, tiled_mma_qk, warp_idx, tid); return; } if (WarpSpecialization::is_epilogue_warp(warp_idx)) { @@ -79,4 +84,4 @@ void prefill_attention_kernel( } } -} // namespace minimax::msa_v1::attention::prefill::q8kv4::detail +} // namespace minimax::msa_v1::attention::prefill::q8kv4::detail diff --git a/inference/msa_v1/attention/prefill/q8kv4/interface.py b/inference/msa_v1/attention/prefill/q8kv4/interface.py index 34587a12..7cd12b18 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/interface.py +++ b/inference/msa_v1/attention/prefill/q8kv4/interface.py @@ -2,22 +2,29 @@ from __future__ import annotations +import logging import math +import os from dataclasses import dataclass import torch -from inference.msa_v1.attention.prefill._common.combine import combine +from inference.msa_v1.attention.prefill._common.combine import LocalityHints, combine from inference.msa_v1.attention.prefill._common.metadata import ( AttentionMetadata, prepare, ) from inference.msa_v1.attention.prefill.q8kv4.jit import load_extension +logger = logging.getLogger(__name__) + _HEAD_DIM = 128 _Q_HEADS_PER_KV = 16 _PAGE_SIZE = 128 _TOPK = 16 +# Set to 0 to keep the split workspace in interleaved device memory on a GPU with several memory +# locality domains, the layout single-domain GPUs use (for A/B measurements). +LOCALITY_DOMAINS_ENV = "MM_SPARSE_PREFILL_Q8KV4_LOCALITY_DOMAINS" def _check_cuda_contiguous(tensor: torch.Tensor, *, name: str) -> None: @@ -37,22 +44,188 @@ def _check_same_device( raise ValueError(f"{name} must be on {reference.device}") +def _locality_domains_disabled() -> bool: + value = os.environ.get(LOCALITY_DOMAINS_ENV, "").strip().lower() or "1" + if value not in ("0", "1", "false", "true"): + raise ValueError(f"{LOCALITY_DOMAINS_ENV} must be 0 or 1, got {value!r}") + return value in ("0", "false") + + +@dataclass(frozen=True) +class _DeviceLocality: + """The memory locality domains of one device: immutable host metadata, no device tensors.""" + + num_domains: int + page_bytes: int + sm_domains: tuple[int, ...] + + +# Probed once per device and process; holds no CUDA tensors, device pointers or workload state. +_device_locality: dict[int, _DeviceLocality | None] = {} + + +def _device_locality_domains(device: torch.device) -> _DeviceLocality | None: + """The locality domains of ``device``, probed once per process; None when it has one.""" + + if _locality_domains_disabled(): + return None + index = device.index + if index not in _device_locality: + extension = load_extension(device) + locality = None + num_domains = int(extension.locality_domain_count(index)) + if num_domains > 1: + try: + locality = _DeviceLocality( + num_domains=num_domains, + page_bytes=int(extension.locality_page_bytes(index)), + sm_domains=tuple(extension.sm_locality_domains(index)), + ) + except RuntimeError as error: + # The probe needs green contexts, which some profilers' driver shims refuse; + # interleaved memory serves every domain then. + logger.warning( + "Q8KV4 prefill: locality-domain probe failed, the split workspace stays " + "interleaved: %s", + error, + ) + if locality is not None: + logger.info( + "Q8KV4 prefill: device %d has %d memory locality domains, the split workspace " + "is striped over them", + index, + locality.num_domains, + ) + _device_locality[index] = locality + return _device_locality[index] + + +class PrefillWorkspace: + """Split workspace of the Q8KV4 prefill: the partial outputs and partial log-sum-exps the + forward kernel writes and the combine reads. + + One workspace serves any number of layers and batches that run in order on one stream; two + streams need two workspaces. On a GPU with several memory locality domains (Rubin, Blackwell) + the partial pages alternate between the domains and the combine reads every tile from the + domain of its own SM; elsewhere the partials are ordinary device memory. ``partial_bytes`` + reserves the partial buffer up front (:meth:`required_bytes` of the largest batch); a batch + that needs more grows it, which on the striped path synchronizes the device first. + """ + + def __init__(self, device: torch.device | str | int, *, partial_bytes: int = 0) -> None: + device = torch.device(device) + if device.type != "cuda": + raise ValueError(f"the prefill workspace lives on a CUDA device, got {device}") + if device.index is None: + device = torch.device("cuda", torch.cuda.current_device()) + self.device = device + self._locality = _device_locality_domains(device) + self._partials: torch.Tensor | None = None + self._lse: torch.Tensor | None = None + self._hints: LocalityHints | None = None + if self._locality is not None: + # The kernel's copy of the SM table and its claim counters, exclusive to this workspace. + self._hints = LocalityHints( + sm_domains=torch.tensor( + self._locality.sm_domains, dtype=torch.int32, device=device + ), + tile_counters=torch.zeros( + self._locality.num_domains, dtype=torch.int32, device=device + ), + page_bytes=self._locality.page_bytes, + ) + if partial_bytes > 0: + self._reserve_partials(int(partial_bytes)) + + @property + def num_domains(self) -> int: + """Memory locality domains the partial buffer is striped over (1: interleaved).""" + + return 1 if self._locality is None else self._locality.num_domains + + def required_bytes(self, total_q: int, num_q_heads: int) -> int: + """Partial-buffer bytes of a batch: 16 slabs of ``total_q x num_q_heads`` BF16 rows, + each padded to the domain stripe.""" + + return _TOPK * self._slab_bytes(total_q, num_q_heads) + + def _slab_bytes(self, total_q: int, num_q_heads: int) -> int: + slab = total_q * num_q_heads * _HEAD_DIM * 2 + if self._locality is None: + return slab + stripe = self._locality.num_domains * self._locality.page_bytes + return -(-slab // stripe) * stripe + + def _reserve_partials(self, nbytes: int) -> None: + if self._locality is None: + self._partials = torch.empty(nbytes, dtype=torch.uint8, device=self.device) + return + stripe = self._locality.num_domains * self._locality.page_bytes + nbytes = -(-nbytes // stripe) * stripe + if self._partials is not None: + # The buffer being replaced may still be read by the previous batch's kernels. + torch.cuda.synchronize(self.device) + extension = load_extension(self.device) + try: + self._partials = extension.alloc_locality_striped(nbytes, self.device.index) + except RuntimeError as error: + # A driver that counts domains but cannot place memory in them: interleaved memory + # serves every domain, without the steering. + logger.warning( + "Q8KV4 prefill: localized allocation failed, the split workspace stays " + "interleaved: %s", + error, + ) + self._locality = None + self._hints = None + self._partials = torch.empty(nbytes, dtype=torch.uint8, device=self.device) + + def split_buffers(self, total_q: int, num_q_heads: int): + """``(o_partial, lse_partial, locality)`` for one batch: ``o_partial`` is + ``[16, total_q, num_q_heads, 128]`` BF16 with padded split slabs, ``lse_partial`` + ``[16, total_q, num_q_heads]`` FP32, ``locality`` the combine's steering hints or None.""" + + slab_bytes = self._slab_bytes(total_q, num_q_heads) + partial_bytes = _TOPK * slab_bytes + if self._partials is None or self._partials.numel() < partial_bytes: + self._reserve_partials(partial_bytes) + # The reservation may have fallen back to interleaved memory, whose slabs are not padded. + slab_bytes = self._slab_bytes(total_q, num_q_heads) + partial_bytes = _TOPK * slab_bytes + o_partial = ( + self._partials[:partial_bytes] + .view(torch.bfloat16) + .as_strided( + (_TOPK, total_q, num_q_heads, _HEAD_DIM), + (slab_bytes // 2, num_q_heads * _HEAD_DIM, _HEAD_DIM, 1), + ) + ) + lse_elements = _TOPK * total_q * num_q_heads + if self._lse is None or self._lse.numel() < lse_elements: + self._lse = torch.empty(lse_elements, dtype=torch.float32, device=self.device) + lse_partial = self._lse[:lse_elements].view(_TOPK, total_q, num_q_heads) + return o_partial, lse_partial, self._hints + + @dataclass(frozen=True) class _PlanState: metadata: AttentionMetadata page_table: torch.Tensor sm_scale: float - o_partial: torch.Tensor - lse_partial: torch.Tensor out: torch.Tensor lse: torch.Tensor class BatchPrefillWithPagedKVCacheWrapper: - """Stateful Q8KV4 sparse-prefill wrapper with reusable scheduling state.""" + """Stateful Q8KV4 sparse-prefill wrapper with reusable scheduling state. + + ``workspace`` holds the split partials between ``plan`` and ``run``; wrappers that run in + order on one stream may share one, and a wrapper without one creates its own. + """ - def __init__(self) -> None: + def __init__(self, workspace: PrefillWorkspace | None = None) -> None: self._plan_state: _PlanState | None = None + self._workspace = workspace def plan( self, @@ -68,7 +241,7 @@ def plan( causal: bool = True, sm_scale: float | None = None, ) -> None: - """Prepare reusable q2k-to-k2q metadata and split-combine workspace.""" + """Prepare reusable q2k-to-k2q metadata and reserve the split workspace.""" if torch.cuda.is_current_stream_capturing(): raise RuntimeError("plan() must be called outside CUDA Graph capture") @@ -101,20 +274,15 @@ def plan( scale = 1.0 / math.sqrt(_HEAD_DIM) if sm_scale is None else float(sm_scale) if not math.isfinite(scale) or scale <= 0.0: raise ValueError("sm_scale must be finite and positive") + device = topk_indices.device + if self._workspace is None or self._workspace.device != device: + self._workspace = PrefillWorkspace(device) + # Reserve now so run() never grows the buffer, not even under graph capture. + self._workspace.split_buffers(total_q, num_q_heads) self._plan_state = _PlanState( metadata=metadata, page_table=page_table, sm_scale=scale, - o_partial=torch.empty( - (_TOPK, total_q, num_q_heads, _HEAD_DIM), - dtype=torch.bfloat16, - **options, - ), - lse_partial=torch.empty( - (_TOPK, total_q, num_q_heads), - dtype=torch.float32, - **options, - ), out=torch.empty( (total_q, num_q_heads, _HEAD_DIM), dtype=torch.bfloat16, @@ -153,7 +321,7 @@ def run( if q.dtype != torch.float8_e4m3fn: raise TypeError("q must be torch.float8_e4m3fn") - num_q_heads = state.out.shape[1] + total_q, num_q_heads = state.out.shape[0], state.out.shape[1] num_kv_heads = num_q_heads // _Q_HEADS_PER_KV if q.shape != state.out.shape: raise ValueError(f"q must have shape {tuple(state.out.shape)}") @@ -205,6 +373,7 @@ def run( ): raise RuntimeError("prepare() returned an incomplete forward schedule") + o_partial, lse_partial, locality = self._workspace.split_buffers(total_q, num_q_heads) load_extension(q.device).run( q, k_cache, @@ -218,23 +387,23 @@ def run( schedule.qsplit_indices, schedule.scheduler_metadata, schedule.work_count, - state.o_partial, - state.lse_partial, + o_partial, + lse_partial, state.sm_scale, + None if locality is None else locality.tile_counters, ) combine( - state.o_partial, - state.lse_partial, + o_partial, + lse_partial, out_tensor, lse_tensor if return_lse or lse is not None else None, - cu_seqlens=state.metadata.cu_seqlens_q, split_counts=schedule.split_counts, use_pdl=True, - raw_partial_stats=False, + locality=locality, ) if return_lse: return out_tensor, lse_tensor return out_tensor -__all__ = ["BatchPrefillWithPagedKVCacheWrapper"] +__all__ = ["LOCALITY_DOMAINS_ENV", "BatchPrefillWithPagedKVCacheWrapper", "PrefillWorkspace"] diff --git a/inference/msa_v1/attention/prefill/q8kv4/jit.py b/inference/msa_v1/attention/prefill/q8kv4/jit.py index a6966187..e36b1735 100644 --- a/inference/msa_v1/attention/prefill/q8kv4/jit.py +++ b/inference/msa_v1/attention/prefill/q8kv4/jit.py @@ -8,7 +8,7 @@ import sys import time from dataclasses import dataclass -from functools import lru_cache +from functools import cache, lru_cache from pathlib import Path import jinja2 @@ -19,8 +19,8 @@ from inference.msa_v1._build_utils import cuda_home as _cuda_home from inference.msa_v1._build_utils import cutlass_root as _cutlass_root from inference.msa_v1._build_utils import require_cuda_version +from inference.msa_v1._build_utils import supports_qmul4 as _probe_supports_qmul4 from inference.msa_v1._build_utils import target_arch as _resolve_target_arch -from inference.msa_v1._build_utils import torch_cuda_arch as _resolve_torch_arch _ROOT = Path(__file__).resolve().parent @@ -28,23 +28,44 @@ _API = _CSRC / "api" _INCLUDE = _CSRC / "include" _TEMPLATES = _CSRC / "templates" +_SUPPORTED_ARCHES = ("100a", "103a", "107a") +_QMUL4_DEQUANT = "qmul4" +_FP16_DEQUANT = "fp16_fallback" @lru_cache(maxsize=1) def _cuda_version() -> tuple[int, int]: return require_cuda_version( (13, 4), - component="Q8KV4 prefill attention with QMUL4", + component="Q8KV4 prefill attention", ) @lru_cache(maxsize=None) def _target_arch(device=None) -> str: - return _resolve_target_arch(device, component="Q8KV4 prefill attention") + arch = _resolve_target_arch( + device, + component="Q8KV4 prefill attention", + supported_arches=_SUPPORTED_ARCHES, + ) + if arch == "107a" and _cuda_version() < (13, 5): + raise RuntimeError( + "Q8KV4 prefill attention on SM107 requires CUDA 13.5 or newer" + ) + return arch + + +@cache +def _supports_qmul4(arch: str) -> bool: + """Return whether the selected NVCC accepts the public QMUL4 PTX form.""" + return _probe_supports_qmul4(arch, probe_root=_cache_root() / "capability_probes") -def _torch_arch(arch: str) -> str: - return _resolve_torch_arch(arch, component="Q8KV4 prefill attention") + +@cache +def _dequant_mode(arch: str) -> str: + # SM107 has no QMUL4; the kernel then dequantizes with exact packed FP16 math. + return _QMUL4_DEQUANT if _supports_qmul4(arch) else _FP16_DEQUANT @lru_cache(maxsize=1) @@ -90,21 +111,23 @@ class JitSpec: """The single compile-time configuration supported by this op.""" target_arch: str + dequant_mode: str variant_name: str = "prefill_attention_q8kv4" q_heads_per_kv: int = 16 head_dim: int = 128 page_size: int = 128 topk: int = 16 - q_stages: int = 3 + q_stages: int = 8 score_stages: int = 2 @property def uri(self) -> str: - return f"{self.variant_name}_{self.target_arch}_{_source_digest()}" + return ( + f"{self.variant_name}_{self.dequant_mode}_{self.target_arch}_" + f"{_source_digest()}" + ) def build_and_load(self): - import torch - cache_dir = _cache_root() / self.uri cache_dir.mkdir(parents=True, exist_ok=True) template = jinja2.Template( @@ -127,6 +150,7 @@ def build_and_load(self): sources = [ _API / "prefill_attention_api.cpp", _API / "prefill_attention_binding.cpp", + _API / "locality_domains.cu", generated_source, ] include_paths = [ @@ -137,9 +161,7 @@ def build_and_load(self): ] started_at = time.time() previous_cuda_home = cpp_extension.CUDA_HOME - previous_arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST") cpp_extension.CUDA_HOME = str(_cuda_home()) - os.environ["TORCH_CUDA_ARCH_LIST"] = _torch_arch(self.target_arch) try: extension = cpp_extension.load( name=module_name, @@ -155,6 +177,17 @@ def build_and_load(self): "--expt-extended-lambda", "-static-global-template-stub=false", "-Xptxas=-O3", + # An explicit gencode keeps torch from adding its own arch list, + # which does not know SM107. + f"-gencode=arch=compute_{self.target_arch}," + f"code=sm_{self.target_arch}", + "-DMINIMAX_MSA_Q8KV4_HAS_QMUL4=" + f"{int(self.dequant_mode == _QMUL4_DEQUANT)}", + # Seen by the host and device passes alike (the cute arch macros are + # device-only), so the kernel instantiation the host registers is the + # one the cubin holds. + "-DMINIMAX_MSA_PREFILL_Q8KV4_SM107=" + f"{int(self.target_arch == '107a')}", "-DCUTLASS_ENABLE_GDC_FOR_SM100", ], extra_ldflags=[ @@ -167,10 +200,6 @@ def build_and_load(self): ) finally: cpp_extension.CUDA_HOME = previous_cuda_home - if previous_arch_list is None: - os.environ.pop("TORCH_CUDA_ARCH_LIST", None) - else: - os.environ["TORCH_CUDA_ARCH_LIST"] = previous_arch_list logger.info( "Compiled inference.msa_v1.attention.prefill.q8kv4 in %.1fs", time.time() - started_at, @@ -181,12 +210,13 @@ def build_and_load(self): def gen_jit_spec(device=None) -> JitSpec: """Return the only production compile-time configuration.""" - return JitSpec(target_arch=_target_arch(device)) + arch = _target_arch(device) + return JitSpec(target_arch=arch, dequant_mode=_dequant_mode(arch)) @lru_cache(maxsize=None) def _load_extension_for_arch(arch: str): - return JitSpec(target_arch=arch).build_and_load() + return JitSpec(target_arch=arch, dequant_mode=_dequant_mode(arch)).build_and_load() def load_extension(device=None): diff --git a/inference/msa_v1/indexer/decode/q8kv4/jit.py b/inference/msa_v1/indexer/decode/q8kv4/jit.py index 6102d610..0588173d 100644 --- a/inference/msa_v1/indexer/decode/q8kv4/jit.py +++ b/inference/msa_v1/indexer/decode/q8kv4/jit.py @@ -5,7 +5,6 @@ import hashlib import logging import os -import subprocess import sys import time from dataclasses import dataclass @@ -18,6 +17,7 @@ from inference.msa_v1._build_utils import cuda_home as _cuda_home from inference.msa_v1._build_utils import cutlass_root as _cutlass_root from inference.msa_v1._build_utils import require_cuda_version +from inference.msa_v1._build_utils import supports_qmul4 as _probe_supports_qmul4 from inference.msa_v1._build_utils import target_arch as _resolve_target_arch from inference.msa_v1._build_utils import torch_cuda_arch as _resolve_torch_arch @@ -30,20 +30,6 @@ _TEMPLATES = _CSRC / "templates" _QMUL4_DEQUANT = "qmul4" _FP16_DEQUANT = "fp16_fallback" -_QMUL4_PROBE_SOURCE = r""" -#include - -__global__ void qmul4_probe(uint32_t* output) { - uint32_t result; - uint16_t packed_e2m1 = 0; - uint32_t scale_e4m3 = 0; - asm volatile( - "mul.rn.satfinite.e4m3x4.e2m1x4.e4m3x4 %0, %1, %2;" - : "=r"(result) - : "h"(packed_e2m1), "r"(scale_e4m3)); - output[0] = result; -} -""".lstrip() @lru_cache(maxsize=1) @@ -105,48 +91,7 @@ def _write_text_if_changed(path: Path, content: str) -> None: def _supports_qmul4(arch: str) -> bool: """Return whether the selected NVCC accepts the public QMUL4 PTX form.""" - nvcc = _cuda_home() / "bin/nvcc" - probe_key = hashlib.sha256() - probe_key.update(str(nvcc.resolve()).encode()) - probe_key.update(str(_cuda_version()).encode()) - probe_key.update(arch.encode()) - probe_key.update(_QMUL4_PROBE_SOURCE.encode()) - probe_dir = _cache_root() / "capability_probes" / probe_key.hexdigest()[:16] - result_path = probe_dir / "qmul4.result" - if result_path.is_file(): - return result_path.read_text(encoding="utf-8").strip() == "supported" - - probe_dir.mkdir(parents=True, exist_ok=True) - source_path = probe_dir / "qmul4_probe.cu" - object_path = probe_dir / f"qmul4_probe.{os.getpid()}.o" - _write_text_if_changed(source_path, _QMUL4_PROBE_SOURCE) - result = subprocess.run( - [ - str(nvcc), - "-std=c++20", - f"-gencode=arch=compute_{arch},code=sm_{arch}", - "-c", - str(source_path), - "-o", - str(object_path), - ], - capture_output=True, - text=True, - check=False, - ) - supported = result.returncode == 0 - if supported: - object_path.unlink(missing_ok=True) - else: - logger.info( - "Selected NVCC does not accept QMUL4 for SM%s; using FP16 dequant fallback", - arch, - ) - _write_text_if_changed( - result_path, - "supported\n" if supported else "unsupported\n", - ) - return supported + return _probe_supports_qmul4(arch, probe_root=_cache_root() / "capability_probes") @cache diff --git a/tests/inference/msa_v1/attention/prefill/q8kv4/test_api_contract.py b/tests/inference/msa_v1/attention/prefill/q8kv4/test_api_contract.py index 0d5d5a0f..2e03fcf3 100644 --- a/tests/inference/msa_v1/attention/prefill/q8kv4/test_api_contract.py +++ b/tests/inference/msa_v1/attention/prefill/q8kv4/test_api_contract.py @@ -14,6 +14,8 @@ ) from inference.msa_v1.attention.prefill.q8kv4 import ( BatchPrefillWithPagedKVCacheWrapper, + PrefillWorkspace, + interface, jit, ) @@ -63,8 +65,11 @@ def _plan_single_page( ) -def test_public_package_exports_only_wrapper() -> None: - assert q8kv4_package.__all__ == ["BatchPrefillWithPagedKVCacheWrapper"] +def test_public_package_exports_wrapper_and_workspace() -> None: + assert q8kv4_package.__all__ == [ + "BatchPrefillWithPagedKVCacheWrapper", + "PrefillWorkspace", + ] def test_prepare_does_not_retain_layout_or_workspace_caches() -> None: @@ -201,6 +206,7 @@ def test_jit_spec_contains_only_compile_time_configuration() -> None: assert tuple(spec.__dataclass_fields__) == ( "target_arch", + "dequant_mode", "variant_name", "q_heads_per_kv", "head_dim", @@ -210,6 +216,7 @@ def test_jit_spec_contains_only_compile_time_configuration() -> None: "score_stages", ) assert spec.variant_name == "prefill_attention_q8kv4" + assert spec.dequant_mode in {"qmul4", "fp16_fallback"} assert spec.topk == 16 @@ -258,3 +265,104 @@ def test_lazy_jit_uses_tensor_device_over_offline_target( assert jit._target_arch(device) == "103a" finally: jit._target_arch.cache_clear() + + +def _run_single_page(workspace: PrefillWorkspace | None, num_kv_heads, batch, length): + topk, cu_seqlens, page_table, q, packed_k, packed_v, scale = _make_single_page_inputs( + num_kv_heads, batch, length + ) + wrapper = BatchPrefillWithPagedKVCacheWrapper(workspace=workspace) + _plan_single_page(wrapper, topk, cu_seqlens, page_table) + out, lse = wrapper.run( + q, (packed_k, packed_v), kv_cache_sf=(scale, scale), return_lse=True + ) + torch.cuda.synchronize() + # Zero K scores: every output row averages the ones in V and the LSE of query ``i`` of a + # request is ln(i + 1), the number of keys its causal window sees. + torch.testing.assert_close(out, torch.ones_like(out), atol=0, rtol=0) + expected_lse = torch.log( + torch.arange(1, length + 1, dtype=torch.float32, device=lse.device) + ).repeat(batch)[:, None].expand_as(lse) + torch.testing.assert_close(lse, expected_lse, atol=1e-5, rtol=1e-5) + return wrapper + + +def test_workspace_serves_batches_in_turn() -> None: + """One split workspace carries batches of growing and then smaller size through separate + wrappers without growing past the largest, and its partial slabs follow the device's + locality-domain stripe.""" + + device = torch.device("cuda", torch.cuda.current_device()) + workspace = PrefillWorkspace(device) + sizes = [] + for num_kv_heads, batch, length in ((1, 1, 1), (4, 1, 8), (4, 2, 3), (1, 2, 3)): + _run_single_page(workspace, num_kv_heads, batch, length) + sizes.append(workspace._partials.numel()) + assert sizes[1] >= sizes[0] and sizes[2] == sizes[1] and sizes[3] == sizes[1] + o_partial, lse_partial, locality = workspace.split_buffers(333, 64) + assert tuple(o_partial.shape) == (16, 333, 64, 128) + assert tuple(lse_partial.shape) == (16, 333, 64) + assert o_partial.stride()[1:] == (64 * 128, 128, 1) + assert workspace.required_bytes(333, 64) == 16 * o_partial.stride(0) * 2 + if workspace.num_domains > 1: + assert locality is not None and locality.num_domains == workspace.num_domains + assert (o_partial.stride(0) * 2) % (locality.num_domains * locality.page_bytes) == 0 + assert locality.tile_counters.numel() == locality.num_domains + else: + assert locality is None and o_partial.is_contiguous() + with pytest.raises(ValueError, match="CUDA device"): + PrefillWorkspace("cpu") + + +def test_workspace_locality_can_be_disabled(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(interface.LOCALITY_DOMAINS_ENV, "0") + workspace = PrefillWorkspace(torch.device("cuda")) + assert workspace.num_domains == 1 + o_partial, _, locality = workspace.split_buffers(5, 64) + assert locality is None and o_partial.is_contiguous() + _run_single_page(workspace, 4, 1, 1) + monkeypatch.setenv(interface.LOCALITY_DOMAINS_ENV, "maybe") + with pytest.raises(ValueError, match="must be 0 or 1"): + PrefillWorkspace(torch.device("cuda")) + + +def test_workspace_falls_back_when_localized_memory_is_unavailable( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A device that counts locality domains but cannot place memory in them keeps the + interleaved workspace, and the batch still runs.""" + + device = torch.device("cuda", torch.cuda.current_device()) + workspace = PrefillWorkspace(device) + if workspace.num_domains == 1: + pytest.skip("device exposes one locality domain") + extension = jit.load_extension(device) + + def refuse(nbytes, index): + raise RuntimeError("localized memory refused for the test") + + monkeypatch.setattr(extension, "alloc_locality_striped", refuse) + o_partial, _, locality = workspace.split_buffers(333, 64) + assert locality is None and workspace.num_domains == 1 and o_partial.is_contiguous() + _run_single_page(workspace, 4, 1, 8) + + +def test_workspace_is_released_with_its_owner() -> None: + """The partial buffer of a dropped wrapper returns to the device.""" + + import gc + + device = torch.device("cuda", torch.cuda.current_device()) + reserve = 512 << 20 + torch.cuda.synchronize() + free_before, _ = torch.cuda.mem_get_info(device) + wrapper = BatchPrefillWithPagedKVCacheWrapper( + PrefillWorkspace(device, partial_bytes=reserve) + ) + free_reserved, _ = torch.cuda.mem_get_info(device) + assert free_before - free_reserved >= reserve // 2 + del wrapper + gc.collect() + torch.cuda.empty_cache() + free_after, _ = torch.cuda.mem_get_info(device) + assert free_after - free_reserved >= reserve // 2 diff --git a/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cases.py b/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cases.py index e24f2202..fbc6a6af 100644 --- a/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cases.py +++ b/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cases.py @@ -29,12 +29,12 @@ logger = logging.getLogger(__name__) -def _require_sm100_or_sm103() -> torch.device: +def _require_supported_device() -> torch.device: if not torch.cuda.is_available(): pytest.skip("CUDA is required") device = torch.device("cuda") - if torch.cuda.get_device_capability(device) not in {(10, 0), (10, 3)}: - pytest.skip("Q8KV4 prefill attention requires SM100 or SM103") + if torch.cuda.get_device_capability(device) not in {(10, 0), (10, 3), (10, 7)}: + pytest.skip("Q8KV4 prefill attention requires SM100, SM103 or SM107") return device @@ -123,6 +123,6 @@ def _run_case(case, device: torch.device, num_kv_heads: int) -> None: def test_real_varlen_attention_cases(case, num_kv_heads: int) -> None: """Check every selected real shape as an independently timed test case.""" - device = _require_sm100_or_sm103() + device = _require_supported_device() _run_case(case, device, num_kv_heads) torch.cuda.empty_cache() diff --git a/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cuda_graph.py b/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cuda_graph.py index 0d1655e4..21441493 100644 --- a/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cuda_graph.py +++ b/tests/inference/msa_v1/attention/prefill/q8kv4/test_real_cuda_graph.py @@ -28,8 +28,8 @@ def test_real_case_cuda_graph_replay(case, num_kv_heads: int) -> None: if not torch.cuda.is_available(): pytest.skip("CUDA is required") device = torch.device("cuda") - if torch.cuda.get_device_capability(device) not in {(10, 0), (10, 3)}: - pytest.skip("Q8KV4 prefill attention requires SM100 or SM103") + if torch.cuda.get_device_capability(device) not in {(10, 0), (10, 3), (10, 7)}: + pytest.skip("Q8KV4 prefill attention requires SM100, SM103 or SM107") inputs = make_real_prefill_attention_inputs( case, device=device, num_kv_heads=num_kv_heads @@ -78,10 +78,12 @@ def test_real_case_cuda_graph_replay(case, num_kv_heads: int) -> None: return_lse=True, ) - state = wrapper._plan_state - assert state is not None - state.o_partial.fill_(-777) - state.lse_partial.fill_(float("nan")) + assert wrapper._plan_state is not None + o_partial, lse_partial, _ = wrapper._workspace.split_buffers( + case.total_q, num_kv_heads * 16 + ) + o_partial.fill_(-777) + lse_partial.fill_(float("nan")) out.fill_(-777) lse.fill_(float("nan")) graph.replay() diff --git a/tests/inference/msa_v1/attention/prefill/test_combine.py b/tests/inference/msa_v1/attention/prefill/test_combine.py new file mode 100644 index 00000000..b86d4502 --- /dev/null +++ b/tests/inference/msa_v1/attention/prefill/test_combine.py @@ -0,0 +1,209 @@ +"""The sparse prefill split combine on its own. + +Random partials and partial LSEs are merged against an FP32 torch reference, with NaN in every +partial slot past a row's valid split count so a masking defect shows up as a non-finite output. +Covers the split counts, head counts, partial and output dtypes, padded split slabs, head counts +whose LSE slabs are not 16-byte aligned, and the per-domain tile claiming of a locality-striped +workspace (with a synthetic SM table, so it runs on any supported GPU). +""" + +from __future__ import annotations + +import logging +import math +import time +from dataclasses import dataclass + +import pytest +import torch + +from inference.msa_v1.attention.prefill._common.combine import LocalityHints, combine + +logger = logging.getLogger(__name__) + +HEAD_DIM = 128 +Q_HEADS_PER_KV = 16 +# One 2 MB page of 256-byte rows: the stripe granularity of a locality-domain workspace. +PAGE_BYTES = 2 << 20 +PAGE_ROWS = PAGE_BYTES // (HEAD_DIM * 2) + + +@dataclass(frozen=True) +class CombineCase: + name: str + total_q: int + num_kv_heads: int + topk: int + partial_dtype: torch.dtype = torch.bfloat16 + out_dtype: torch.dtype = torch.bfloat16 + # Query heads per KV head; a total head count that is not a multiple of 4 leaves the flat + # row count unaligned for a 2-D LSE box. + q_heads_per_kv: int = Q_HEADS_PER_KV + split_counts: bool = True + lse_out: bool = True + # Pad every split slab to a multiple of this many flat rows (0: contiguous slabs). + slab_rows: int = 0 + # Claim tiles per memory locality domain over a synthetic SM table (0: tile = CTA index). + domains: int = 0 + + +CASES = ( + CombineCase("h64_topk16", 333, 4, 16), + # 16 heads: the flat rows are not a multiple of the tile, so the last tile is partial + CombineCase("h16_topk16_partial_tile", 171, 1, 16), + CombineCase("h32_topk4", 100, 2, 4), + CombineCase("h64_topk8_f16_partials", 257, 4, 8, partial_dtype=torch.float16), + CombineCase("h64_topk32", 129, 4, 32), + CombineCase("h64_topk16_every_split", 65, 4, 16, split_counts=False, lse_out=False), + CombineCase("one_query_f16_out", 1, 1, 16, out_dtype=torch.float16), + CombineCase("h64_topk16_padded_slabs", 333, 4, 16, slab_rows=1024), + CombineCase("h64_topk16_two_domains", 333, 4, 16, slab_rows=2 * PAGE_ROWS, domains=2), + CombineCase( + "h16_topk8_two_domains_partial_tile", 171, 1, 8, slab_rows=2 * PAGE_ROWS, domains=2 + ), + # Flat row counts 333, 342 and 606: no split slab starts 16-byte aligned + CombineCase("h1_topk16_odd_rows", 333, 1, 16, q_heads_per_kv=1), + CombineCase("h2_topk8_f16_partials", 171, 1, 8, partial_dtype=torch.float16, q_heads_per_kv=2), + CombineCase("h6_topk32_odd_rows", 101, 2, 32, q_heads_per_kv=3), +) + + +def _require_supported_device() -> torch.device: + if not torch.cuda.is_available(): + pytest.skip("CUDA is required") + device = torch.device("cuda") + if torch.cuda.get_device_capability(device) not in {(10, 0), (10, 3), (10, 7)}: + pytest.skip("the prefill combine requires SM100, SM103 or SM107") + return device + + +def _real_to_fake_col(device: torch.device) -> torch.Tensor: + """Fake (stored) column of every real column: inside each 32-column group the forward + epilogue stores a 4x4 transpose of the 32-bit pairs.""" + col = torch.arange(HEAD_DIM, device=device) + group_base, col32 = col // 32 * 32, col % 32 + return group_base + (col32 % 8) // 2 * 8 + col32 // 8 * 2 + col32 % 2 + + +def _reference(partial, lse, valid): + """FP32 merge of the valid splits: softmax weights over the partial LSEs, final LSE.""" + lse = torch.where(valid, lse, torch.full_like(lse, -math.inf)) + row_max = lse.amax(dim=0) + safe_max = torch.where(torch.isinf(row_max), torch.zeros_like(row_max), row_max) + weight = torch.exp(lse - safe_max) + total = weight.sum(dim=0) + inv_total = torch.where(total > 0, 1.0 / total, torch.zeros_like(total)) + partial = torch.where( + valid[..., None], partial.float(), torch.zeros_like(partial, dtype=torch.float32) + ) + out = ((weight * inv_total)[..., None] * partial).sum(dim=0) + final_lse = torch.where( + total > 0, row_max + torch.log(total), torch.full_like(row_max, -math.inf) + ) + return out, final_lse + + +def _nan_fill(tensor: torch.Tensor, mask: torch.Tensor) -> None: + """Write a quiet NaN into every element selected by ``mask`` (broadcast over trailing dims).""" + nan = torch.tensor(math.nan, dtype=tensor.dtype, device=tensor.device) + tensor.masked_fill_(mask.reshape(mask.shape + (1,) * (tensor.ndim - mask.ndim)), nan) + + +@pytest.mark.parametrize("case", CASES, ids=lambda c: c.name) +def test_combine_merges_the_valid_splits(case: CombineCase) -> None: + device = _require_supported_device() + gen = torch.Generator(device=device).manual_seed(hash(case.name) & 0xFFFF) + heads = case.num_kv_heads * case.q_heads_per_kv + shape = (case.topk, case.total_q, heads) + + partial_real = torch.randn(*shape, HEAD_DIM, generator=gen, device=device).to( + case.partial_dtype + ) + # Partial LSEs spread over a few units with a row offset, so the row max sits in a random split. + lse_partial = torch.randn(*shape, generator=gen, device=device) * 2.0 + lse_partial += torch.randn(case.total_q, heads, generator=gen, device=device) * 4.0 + if case.split_counts: + split_counts = torch.randint( + 1, + case.topk + 1, + (case.total_q, case.num_kv_heads), + generator=gen, + device=device, + dtype=torch.int32, + ) + split_counts[0::7] = case.topk + split_counts[3::11] = 1 + counts_q = split_counts.repeat_interleave(case.q_heads_per_kv, dim=1) + else: + split_counts = None + counts_q = torch.full((case.total_q, heads), case.topk, device=device, dtype=torch.int32) + valid = torch.arange(case.topk, device=device)[:, None, None] < counts_q[None] + + ref_out, ref_lse = _reference(partial_real, lse_partial, valid) + + # The kernel's inputs: fake column order, and NaN wherever a split is past the row's count + # (and in the slab padding, which no tile may read). + flat_rows = case.total_q * heads + slab_rows = ( + flat_rows if case.slab_rows == 0 else -(-flat_rows // case.slab_rows) * case.slab_rows + ) + o_partial = torch.full( + (case.topk * slab_rows * HEAD_DIM,), math.nan, dtype=case.partial_dtype, device=device + ).as_strided( + (case.topk, case.total_q, heads, HEAD_DIM), + (slab_rows * HEAD_DIM, heads * HEAD_DIM, HEAD_DIM, 1), + ) + o_partial[..., _real_to_fake_col(device)] = partial_real + _nan_fill(o_partial, ~valid) + locality = None + if case.domains: + locality = LocalityHints( + sm_domains=torch.arange(4096, dtype=torch.int32, device=device) % case.domains, + tile_counters=torch.zeros(case.domains, dtype=torch.int32, device=device), + page_bytes=PAGE_BYTES, + ) + lse_in = lse_partial.clone() + _nan_fill(lse_in, ~valid) + out = torch.empty(case.total_q, heads, HEAD_DIM, dtype=case.out_dtype, device=device) + lse_out = ( + torch.empty(case.total_q, heads, dtype=torch.float32, device=device) + if case.lse_out + else None + ) + + def run(): + if locality is not None: + # Zero at launch is the contract; the forward kernel does it in production. + locality.tile_counters.zero_() + combine( + o_partial, + lse_in, + out, + lse_out, + split_counts=split_counts, + use_pdl=True, + locality=locality, + ) + return out.clone(), None if lse_out is None else lse_out.clone() + + torch.cuda.synchronize() + started = time.perf_counter() + first = run() + torch.cuda.synchronize() + logger.info("combine %s: first call (compile + run) %.3fs", case.name, time.perf_counter() - started) + started = time.perf_counter() + second = run() + torch.cuda.synchronize() + logger.info("combine %s: ran in %.3fms", case.name, (time.perf_counter() - started) * 1e3) + + if locality is not None: # every CTA claimed exactly once + assert int(locality.tile_counters.sum()) >= -(-case.total_q * heads // 64) + assert torch.isfinite(first[0]).all(), "a stale partial reached the output" + # The output is the FP32 merge rounded once to the output dtype. + torch.testing.assert_close(first[0].float(), ref_out, rtol=1e-2, atol=2e-2) + if case.lse_out: + assert torch.isfinite(first[1]).all() + torch.testing.assert_close(first[1], ref_lse, rtol=1e-5, atol=1e-4) + # Same inputs, same split order: the merge is deterministic. + for a, b in zip(first, second): + assert a is None or torch.equal(a, b), f"{case.name}: the combine is not deterministic" diff --git a/tests/inference/msa_v1/attention/test_probability_contract.py b/tests/inference/msa_v1/attention/test_probability_contract.py index e50eda72..f2167d06 100644 --- a/tests/inference/msa_v1/attention/test_probability_contract.py +++ b/tests/inference/msa_v1/attention/test_probability_contract.py @@ -392,6 +392,7 @@ def _verify_cpp(root, scores, maxima, scales, reference, reference_p): "-Xcompiler=-fPIC", "--expt-relaxed-constexpr", "-DMINIMAX_MSA_Q8KV4_HAS_QMUL4=1", + "-DMINIMAX_MSA_PREFILL_Q8KV4_SM107=0", "-I" + str(repo / "third_party/cutlass/include"), "-I" + str(prefill), "-I" + str(decode / "collective"),