mirror of
https://github.com/ROCm/composable_kernel.git
synced 2026-05-21 05:19:20 +00:00
[CK] [CK_Tile] Add FMHA scaffolding to CK kernel dispatcher (#5260) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Motivation The CK Tile dispatcher currently supports GEMM and Grouped Convolution but has no support for Fused Multi-Head Attention (FMHA). The example/ck_tile/01_fmha folder contains a comprehensive FMHA implementation with forward, backward, split-KV, paged-KV, append-KV, and batch-prefill kernels across multiple GPU architectures — but there is no unified dispatch layer for it. This PR ports the FMHA stack into the dispatcher, following the same architectural patterns established by GEMM and Grouped Convolution, enabling runtime kernel selection, JIT compilation from Python, and a declarative C++ example flow. Autotuning heuristics to follow. ## Technical Details This PR adds FMHA scaffolding to the CK dispatcher framework, mirroring GEMM's layered architecture. Seven new C++ runtime headers provide type definitions (coexisting with upstream headers via __has_include, requiring zero modifications to example/ck_tile/01_fmha/), a problem builder with 18+ setters, Signature + Algorithm kernel key matching, a virtual kernel instance, a DECL_FMHA_KERNEL_SET macro with wildcard support and named tile/wave/warp setters, arch-aware registry with JSON export, and a dispatcher with seqtune-aware selection, configurable timing, and multi-stage execution plans for split-KV (two-stage) and backward (three-stage). The codegen pipeline is driven by a fmha_arch_specs.json capturing per-arch tile tables and pipeline constraints for five architectures (gfx90a/942/950/1100/1201), migrated from hardcoded logic in 01_fmha/codegen/, with supporting modules for C++ symbol mappings, validation rules, and named receipt profiles (ck_default, flash, pytorch, aiter, fp32, fp8). Python integration (fmha_utils.py) mirrors the C++ layer with JIT compilation, parallel multi-kernel builds, HIP memory management via ctypes, tolerance-based validation, and a NumPy CPU reference with GQA support. Twenty-seven C++ and thirty-two Python examples cover the full feature surface — forward, split-KV, masks, bias, dropout, GQA, backward, append-KV, batch prefill, fp8, logits soft cap, sink tokens, and parameter sweeps — all JIT-compiled on the fly. ## Test Plan Seven test files cover the runtime types, codegen, and end-to-end correctness. C++ unit tests validate the problem builder, dispatcher planning (single-stage for forward/paged-KV/append-KV; multi-stage for split-KV and backward), registry operations, and the kernel-set declaration macro. Python unit tests verify codegen emission, profile filtering, and 15 validation rules for masks, hdim constraints, and pipeline requirements. GPU execution validation in 01_basic_fmha --validate reports zero errors across 65,536 elements with max absolute error of 7.29e-05. A gold-standard parity suite (test_fmha_parity.py) runs 14 configurations through both the upstream tile_example_fmha_fwd and the dispatcher, comparing exit codes to confirm behavioral parity — all 14 match. ## Test Result The C++ smoke test builds and passes all 9 compiled examples, and a Python JIT sweep (29_sweep_seqlen.py) passes 7/7 configurations reaching up to 375 TFLOPS at seqlen 2048. ## Submission Checklist - [x] Look over the contributing guidelines at https://github.com/ROCm/ROCm/blob/develop/CONTRIBUTING.md#pull-requests.
149 lines
4.2 KiB
Python
149 lines
4.2 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
"""
|
|
Example 02: Multi-Shape FMHA
|
|
|
|
Runs FMHA forward with a single kernel across multiple problem shapes
|
|
(varying batch, sequence length, and head count).
|
|
|
|
Usage:
|
|
python3 02_multi_shape.py
|
|
python3 02_multi_shape.py --help
|
|
python3 02_multi_shape.py --dtype bf16
|
|
"""
|
|
|
|
import sys
|
|
import argparse
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent / "python"))
|
|
import numpy as np
|
|
|
|
from fmha_utils import (
|
|
FmhaKernelSpec,
|
|
FmhaProblem,
|
|
detect_gpu_arch,
|
|
setup_fmha_dispatcher,
|
|
spec_to_config,
|
|
)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Multi-Shape FMHA Example - runs multiple shapes",
|
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog="""
|
|
Examples:
|
|
python3 02_multi_shape.py # Default FP16
|
|
python3 02_multi_shape.py --dtype bf16 # BF16 FMHA
|
|
""",
|
|
)
|
|
parser.add_argument(
|
|
"--dtype",
|
|
default="fp16",
|
|
choices=["fp16", "bf16"],
|
|
help="Data type (default: fp16)",
|
|
)
|
|
parser.add_argument(
|
|
"--arch",
|
|
default=detect_gpu_arch(),
|
|
help="Target architecture (auto-detected from rocminfo)",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
print("=" * 70)
|
|
print("Example 02: Multi-Shape FMHA")
|
|
print("=" * 70)
|
|
|
|
# Step 1: Setup dispatcher
|
|
print("\nStep 1: Setup Dispatcher")
|
|
|
|
# FmhaKernelSpec fields:
|
|
# name -- human-readable kernel identifier
|
|
# hdim -- head dimension (hdim_q = hdim_v)
|
|
# pipeline -- "qr_async" (async prefetch) or "qr" (synchronous)
|
|
# tile_m0 -- Stage 0 tile along seqlen_q (Q*K^T M dimension)
|
|
# tile_n0 -- Stage 0 tile along seqlen_k (Q*K^T N dimension)
|
|
# tile_k0 -- Stage 0 tile along hdim_q (Q*K^T K dimension)
|
|
spec = FmhaKernelSpec(name="multi_shape", hdim=128, pipeline="qr_async")
|
|
config = spec_to_config(spec, dtype=args.dtype, arch=args.arch)
|
|
|
|
setup = setup_fmha_dispatcher(config, verbose=True)
|
|
if not setup.success:
|
|
print(f" ERROR: {setup.error}")
|
|
return 1
|
|
|
|
runner = setup.runner
|
|
print(f" Library: {setup.library_path}")
|
|
print(f" Build: {setup.build_time_s:.1f} s")
|
|
|
|
# Step 2: Run batch of different shapes
|
|
print("\nStep 2: Run Shapes")
|
|
|
|
shapes = [
|
|
# (batch, nhead_q, nhead_k, seqlen_q, seqlen_k, hdim)
|
|
(1, 4, 4, 64, 64, 128),
|
|
(2, 8, 8, 128, 128, 128),
|
|
(4, 8, 8, 128, 128, 128),
|
|
(1, 16, 16, 256, 256, 128),
|
|
(2, 8, 8, 256, 256, 128),
|
|
(1, 8, 8, 512, 512, 128),
|
|
(2, 4, 4, 512, 512, 128),
|
|
(1, 8, 8, 1024, 1024, 128),
|
|
]
|
|
|
|
print(f"\n {'#':<3} {'Shape':<36} {'Time(ms)':>10} {'TFLOPS':>10} {'Status':>8}")
|
|
print(" " + "-" * 70)
|
|
|
|
total_ops = 0
|
|
total_time = 0.0
|
|
|
|
for idx, (b, hq, hk, sq, sk, d) in enumerate(shapes, 1):
|
|
prob = FmhaProblem(
|
|
batch=b,
|
|
nhead_q=hq,
|
|
nhead_k=hk,
|
|
seqlen_q=sq,
|
|
seqlen_k=sk,
|
|
hdim_q=d,
|
|
hdim_v=d,
|
|
)
|
|
shape_str = f"B{b}_Hq{hq}_Hk{hk}_S{sq}x{sk}_D{d}"
|
|
|
|
np.random.seed(42 + idx)
|
|
Q = (np.random.randn(*prob.q_shape()) * 0.1).astype(np.float16)
|
|
K = (np.random.randn(*prob.k_shape()) * 0.1).astype(np.float16)
|
|
V = (np.random.randn(*prob.v_shape()) * 0.1).astype(np.float16)
|
|
|
|
result = runner.run(Q, K, V, prob)
|
|
|
|
if result.success:
|
|
total_ops += prob.num_ops
|
|
total_time += result.time_ms
|
|
print(
|
|
f" {idx:<3} {shape_str:<36} {result.time_ms:>10.4f} {result.tflops:>10.2f} {'OK':>8}"
|
|
)
|
|
else:
|
|
print(f" {idx:<3} {shape_str:<36} {'N/A':>10} {'N/A':>10} {'Error':>8}")
|
|
|
|
print(" " + "-" * 70)
|
|
|
|
if total_time > 0:
|
|
avg_tflops = (total_ops / 1e12) / (total_time / 1000)
|
|
print(f"\n Total: {total_time:.2f} ms, Average: {avg_tflops:.2f} TFLOPS")
|
|
|
|
runner.cleanup()
|
|
|
|
print("\n" + "=" * 70)
|
|
print("Multi-Shape FMHA complete!")
|
|
print("=" * 70)
|
|
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|