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.
64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
"""Generic multi-GPU parallel job runner for tile engine benchmarks.
|
|
|
|
Op-agnostic: takes opaque jobs, distributes them across GPUs with one
|
|
job per GPU at a time, and yields results in completion order. Used by
|
|
fmha_benchmark.py and reusable for gemm/reduce/pooling benchmarks.
|
|
"""
|
|
|
|
import threading
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from typing import Any, Callable, Iterator, List, Optional, Tuple
|
|
|
|
|
|
def run_parallel_on_gpus(
|
|
jobs: List[Any],
|
|
gpu_ids: List[int],
|
|
run_one: Callable[[Any, int], Any],
|
|
max_workers: Optional[int] = None,
|
|
) -> Iterator[Tuple[int, Any]]:
|
|
"""Dispatch jobs across GPUs, one job per GPU at a time.
|
|
|
|
Args:
|
|
jobs: Opaque job objects passed to run_one.
|
|
gpu_ids: GPU IDs to use (e.g. [0,1,2,3]). At most one job per GPU runs concurrently.
|
|
run_one: Callable run_one(job, gpu_id) -> result. Caller is responsible
|
|
for any subprocess isolation, environment setup, etc.
|
|
max_workers: Thread pool size. Defaults to len(gpu_ids).
|
|
|
|
Yields:
|
|
(job_index, result) tuples in completion order. Caller can sort by
|
|
job_index to restore submission order if needed.
|
|
"""
|
|
if not jobs:
|
|
return
|
|
if max_workers is None:
|
|
max_workers = len(gpu_ids)
|
|
|
|
# One job per GPU at a time
|
|
gpu_semas = {gid: threading.Semaphore(1) for gid in gpu_ids}
|
|
cycle = [0]
|
|
cycle_lock = threading.Lock()
|
|
|
|
def _pick_gpu() -> int:
|
|
with cycle_lock:
|
|
gid = gpu_ids[cycle[0] % len(gpu_ids)]
|
|
cycle[0] += 1
|
|
return gid
|
|
|
|
def _wrapper(job_idx: int, job: Any) -> Tuple[int, Any]:
|
|
gid = _pick_gpu()
|
|
gpu_semas[gid].acquire()
|
|
try:
|
|
return job_idx, run_one(job, gid)
|
|
finally:
|
|
gpu_semas[gid].release()
|
|
|
|
with ThreadPoolExecutor(max_workers=max_workers) as pool:
|
|
futures = [pool.submit(_wrapper, i, j) for i, j in enumerate(jobs)]
|
|
for fut in as_completed(futures):
|
|
yield fut.result()
|