Files
composable_kernel/dispatcher/scripts/parallel_kernel_builder.py
Vidyasagar Ananthan 86591de476 [rocm-libraries] ROCm/rocm-libraries#5260 (commit a1834d2)
[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.
2026-05-17 07:30:33 +00:00

147 lines
4.3 KiB
Python
Executable File

#!/usr/bin/env python3
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT
"""
Build kernels in parallel - one translation unit per kernel.
This script is called at make time (not cmake time) to avoid slow cmake configuration.
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor, as_completed
def find_hipcc():
"""Find hipcc compiler."""
candidates = [
os.environ.get("HIPCC"),
"/opt/rocm/bin/hipcc",
shutil.which("hipcc") if shutil else None,
]
for path in candidates:
if path and os.path.isfile(path):
return path
return "hipcc" # Assume in PATH
def compile_kernel(args):
"""Compile a single kernel."""
if len(args) == 5:
kernel_hpp, output_dir, include_dirs, hipcc, arch = args
else:
kernel_hpp, output_dir, include_dirs, hipcc = args
arch = "gfx942"
kernel_name = kernel_hpp.stem
# Create wrapper .cpp
wrapper_cpp = output_dir / f"{kernel_name}.cpp"
wrapper_cpp.write_text(f'''// Auto-generated wrapper
#include "{kernel_hpp.name}"
namespace {{ volatile bool _k = true; }}
''')
# Compile to object
obj_file = output_dir / f"{kernel_name}.o"
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "python"))
from fmha_utils import fmha_compile_flags # noqa: E402
# arch is extracted from work tuple above
cmd = fmha_compile_flags(arch, hipcc, family="bwd")
for inc_dir in include_dirs:
cmd.extend(["-I", str(inc_dir)])
cmd.extend(["-I", str(kernel_hpp.parent)])
cmd.extend(["-o", str(obj_file), str(wrapper_cpp)])
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
return (kernel_name, False, result.stderr)
return (kernel_name, True, str(obj_file))
def main():
parser = argparse.ArgumentParser(description="Build kernels in parallel")
parser.add_argument("--kernel-dir", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--include-dirs", type=str, required=True)
parser.add_argument("--jobs", type=int, default=os.cpu_count())
parser.add_argument(
"--arch",
type=str,
default="gfx942",
help="GPU architecture target (default: gfx942)",
)
args = parser.parse_args()
# Find kernel headers
kernel_headers = list(args.kernel_dir.glob("gemm_*.hpp")) + list(
args.kernel_dir.glob("conv_*.hpp")
)
if not kernel_headers:
print("No kernels found to build")
return 0
print(f"Building {len(kernel_headers)} kernels with {args.jobs} parallel jobs...")
include_dirs = [Path(p.strip()) for p in args.include_dirs.split(",")]
hipcc = find_hipcc()
args.output_dir.mkdir(parents=True, exist_ok=True)
# Prepare work items
work = [
(h, args.output_dir, include_dirs, hipcc, args.arch) for h in kernel_headers
]
# Compile in parallel
obj_files = []
failed = []
with ProcessPoolExecutor(max_workers=args.jobs) as executor:
futures = {executor.submit(compile_kernel, w): w[0].name for w in work}
for i, future in enumerate(as_completed(futures), 1):
name, success, result = future.result()
if success:
obj_files.append(result)
print(f"[{i}/{len(kernel_headers)}] Built: {name}")
else:
failed.append((name, result))
print(f"[{i}/{len(kernel_headers)}] FAILED: {name}")
if failed:
print(f"\n{len(failed)} kernels failed to compile:")
for name, err in failed[:5]:
print(f" {name}: {err[:100]}")
return 1
# Link into shared library
print(f"\nLinking {len(obj_files)} objects into libdispatcher_kernels.so...")
lib_path = args.output_dir / "libdispatcher_kernels.so"
link_cmd = [hipcc, "-shared", "-fPIC", "-o", str(lib_path)] + obj_files
result = subprocess.run(link_cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f"Linking failed: {result.stderr}")
return 1
print(f"OK Built: {lib_path}")
return 0
if __name__ == "__main__":
import shutil
sys.exit(main())