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.
179 lines
5.3 KiB
Python
179 lines
5.3 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
"""
|
|
Example 32: Sweep Head Dimension
|
|
|
|
Demonstrates FMHA across different head dimensions (32, 64, 128, 256).
|
|
The prebuilt library only supports hdim=128; other head dimensions are
|
|
validated via CPU reference only.
|
|
|
|
Fixed: batch=2, nhead=8, seqlen=128
|
|
Sweep: hdim in [32, 64, 128, 256]
|
|
|
|
Usage:
|
|
python3 32_sweep_hdim.py
|
|
python3 32_sweep_hdim.py --arch gfx942
|
|
"""
|
|
|
|
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 (
|
|
FmhaKernelConfig,
|
|
FmhaProblem,
|
|
FmhaValidator,
|
|
cpu_attention_fwd,
|
|
detect_gpu_arch,
|
|
setup_fmha_dispatcher,
|
|
)
|
|
|
|
BATCH = 2
|
|
NHEAD = 8
|
|
SEQLEN = 128
|
|
HDIMS = [32, 64, 128, 256]
|
|
GPU_SUPPORTED_HDIM = 128
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Sweep Head Dimension FMHA")
|
|
parser.add_argument("--arch", default=detect_gpu_arch())
|
|
args = parser.parse_args()
|
|
|
|
print("=" * 70)
|
|
print("Example 32: Sweep Head Dimension")
|
|
print("=" * 70)
|
|
|
|
print(f"\n Fixed: batch={BATCH}, nhead={NHEAD}, seqlen={SEQLEN}")
|
|
print(f" Sweep: hdim in {HDIMS}")
|
|
print(f" Arch: {args.arch}")
|
|
print(f" Note: Only hdim={GPU_SUPPORTED_HDIM} runs on GPU (prebuilt lib)")
|
|
|
|
validator = FmhaValidator(rtol=1e-2, atol=1e-2)
|
|
|
|
# Step 1: JIT-compile FMHA kernel (hdim=128)
|
|
print("\nStep 1: JIT-Compile FMHA Kernel")
|
|
config = FmhaKernelConfig(
|
|
data_type="fp16",
|
|
hdim_q=GPU_SUPPORTED_HDIM,
|
|
hdim_v=GPU_SUPPORTED_HDIM,
|
|
gfx_arch=args.arch,
|
|
)
|
|
setup = setup_fmha_dispatcher(config)
|
|
runner = None
|
|
if not setup.success:
|
|
print(f" JIT build failed: {setup.error}")
|
|
print(" Will run CPU reference only")
|
|
else:
|
|
runner = setup.runner
|
|
print(f" JIT build: {setup.build_time_s:.1f}s")
|
|
|
|
# Step 2: CPU reference for all hdims
|
|
print("\nStep 2: CPU Reference for All Head Dimensions")
|
|
|
|
np.random.seed(42)
|
|
cpu_data = {}
|
|
|
|
print(
|
|
f"\n {'hdim':>6} | {'Scale':>8} | {'FLOPs':>14} | {'O Range':>22} | {'Finite':<6}"
|
|
)
|
|
print(" " + "-" * 66)
|
|
|
|
for hdim in HDIMS:
|
|
prob = FmhaProblem(
|
|
batch=BATCH,
|
|
nhead_q=NHEAD,
|
|
nhead_k=NHEAD,
|
|
seqlen_q=SEQLEN,
|
|
seqlen_k=SEQLEN,
|
|
hdim_q=hdim,
|
|
hdim_v=hdim,
|
|
)
|
|
|
|
Q = (np.random.randn(*prob.q_shape()) * 0.1).astype(np.float32)
|
|
K = (np.random.randn(*prob.k_shape()) * 0.1).astype(np.float32)
|
|
V = (np.random.randn(*prob.v_shape()) * 0.1).astype(np.float32)
|
|
|
|
O_ref = cpu_attention_fwd(Q, K, V, prob.scale)
|
|
is_finite = bool(np.all(np.isfinite(O_ref)))
|
|
o_range = f"[{O_ref.min():.4f}, {O_ref.max():.4f}]"
|
|
|
|
print(
|
|
f" {hdim:>6} | {prob.scale:>8.4f} | {prob.num_ops:>14,} | {o_range:>22} | {'OK' if is_finite else 'NaN!':<6}"
|
|
)
|
|
cpu_data[hdim] = (Q, K, V, O_ref, prob)
|
|
|
|
# Step 3: GPU sweep (only hdim=128 supported)
|
|
print("\nStep 3: GPU Sweep")
|
|
|
|
hdr = f" {'hdim':>6} | {'Time(ms)':>10} | {'TFLOPS':>10} | {'MaxErr':>10} | {'Status':<10}"
|
|
print(f"\n{hdr}")
|
|
print(" " + "-" * 60)
|
|
|
|
results = []
|
|
|
|
for hdim in HDIMS:
|
|
Q, K, V, O_ref, prob = cpu_data[hdim]
|
|
|
|
if hdim != GPU_SUPPORTED_HDIM or runner is None:
|
|
print(
|
|
f" {hdim:>6} | {'---':>10} | {'---':>10} | {'---':>10} | {'CPU only':<10}"
|
|
)
|
|
results.append((hdim, True, 0.0, 0.0, 0.0))
|
|
continue
|
|
|
|
Q_f16 = Q.astype(np.float16)
|
|
K_f16 = K.astype(np.float16)
|
|
V_f16 = V.astype(np.float16)
|
|
|
|
res = runner.run(Q_f16, K_f16, V_f16, prob)
|
|
if not res.success:
|
|
print(
|
|
f" {hdim:>6} | {'---':>10} | {'---':>10} | {'---':>10} | {'FAIL':<10}"
|
|
)
|
|
results.append((hdim, False, 0.0, 0.0, 0.0))
|
|
continue
|
|
|
|
max_err = float(np.abs(res.output.astype(np.float32) - O_ref).max())
|
|
ok, _, _ = validator.check(res.output, O_ref)
|
|
tag = "PASS" if ok else "FAIL"
|
|
|
|
print(
|
|
f" {hdim:>6} | {res.time_ms:>10.4f} | {res.tflops:>10.2f} | {max_err:>10.2e} | {tag:<10}"
|
|
)
|
|
results.append((hdim, ok, res.time_ms, res.tflops, max_err))
|
|
|
|
# Step 4: hdim analysis
|
|
print("\nStep 4: Head Dimension Analysis")
|
|
print(" Each hdim requires a dedicated compiled kernel:")
|
|
for hdim in HDIMS:
|
|
gpu_status = "prebuilt" if hdim == GPU_SUPPORTED_HDIM else "needs JIT"
|
|
tile_hint = f"tile_k0max={hdim}"
|
|
print(f" hdim={hdim:>3}: {gpu_status:<10} ({tile_hint})")
|
|
|
|
print("\n Compute scales linearly with hdim (via Q*K^T and attn*V).")
|
|
print(" Larger hdim = more work per token, fewer tokens processed per CU.")
|
|
|
|
# Summary
|
|
passed = sum(1 for _, ok, *_ in results if ok)
|
|
total = len(results)
|
|
print("\n" + "=" * 70)
|
|
print(f" Results: {passed}/{total} passed")
|
|
print(f" Fixed: B={BATCH} H={NHEAD} S={SEQLEN}")
|
|
print(f" Sweep: hdim={HDIMS}")
|
|
print(f" GPU: hdim={GPU_SUPPORTED_HDIM} only (prebuilt)")
|
|
print(f" Status: {'PASS' if passed == total else 'FAIL'}")
|
|
print("=" * 70)
|
|
|
|
return 0 if passed == total else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|