Files
composable_kernel/dispatcher/examples/fmha/python/30_sweep_batch.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

152 lines
4.3 KiB
Python

#!/usr/bin/env python3
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT
"""
Example 30: Sweep Batch Size
Demonstrates how FMHA performance scales with batch size.
FMHA compute scales linearly with batch, so time should increase
linearly while TFLOPS remains roughly constant once the GPU is saturated.
Fixed: seqlen=128, nhead=8, hdim=128
Sweep: batch in [1, 2, 4, 8, 16, 32]
Usage:
python3 30_sweep_batch.py
python3 30_sweep_batch.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,
)
SEQLEN = 128
NHEAD = 8
HDIM = 128
BATCHES = [1, 2, 4, 8, 16, 32]
def main():
parser = argparse.ArgumentParser(description="Sweep Batch Size FMHA")
parser.add_argument("--arch", default=detect_gpu_arch())
args = parser.parse_args()
print("=" * 70)
print("Example 30: Sweep Batch Size")
print("=" * 70)
print(f"\n Fixed: seqlen={SEQLEN}, nhead={NHEAD}, hdim={HDIM}")
print(f" Sweep: batch in {BATCHES}")
print(f" Arch: {args.arch}")
validator = FmhaValidator(rtol=1e-2, atol=1e-2)
# Step 1: JIT-compile FMHA kernel
print("\nStep 1: JIT-Compile FMHA Kernel")
config = FmhaKernelConfig(
data_type="fp16",
hdim_q=HDIM,
hdim_v=HDIM,
gfx_arch=args.arch,
)
setup = setup_fmha_dispatcher(config)
if not setup.success:
print(f" JIT build failed: {setup.error}")
return 1
runner = setup.runner
print(f" JIT build: {setup.build_time_s:.1f}s")
# Step 2: Sweep
print("\nStep 2: Batch Size Sweep")
hdr = f" {'Batch':>8} | {'Time(ms)':>10} | {'TFLOPS':>10} | {'MaxErr':>10} | {'Status':<6}"
print(f"\n{hdr}")
print(" " + "-" * 60)
np.random.seed(42)
results = []
for batch in BATCHES:
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.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)
O_ref = cpu_attention_fwd(
Q.astype(np.float32),
K.astype(np.float32),
V.astype(np.float32),
prob.scale,
)
res = runner.run(Q, K, V, prob)
if not res.success:
print(
f" {batch:>8} | {'---':>10} | {'---':>10} | {'---':>10} | {'FAIL':<6}"
)
results.append((batch, 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" {batch:>8} | {res.time_ms:>10.4f} | {res.tflops:>10.2f} | {max_err:>10.2e} | {tag:<6}"
)
results.append((batch, ok, res.time_ms, res.tflops, max_err))
# Step 3: Linearity analysis
print("\nStep 3: Linear Scaling Analysis")
valid = [(b, t, tf) for b, ok, t, tf, _ in results if ok and t > 0]
if len(valid) >= 2:
b0, t0, tf0 = valid[0]
b_last, t_last, tf_last = valid[-1]
batch_ratio = b_last / b0
time_ratio = t_last / t0
linearity = time_ratio / batch_ratio
print(
f" Batch {b0} -> {b_last}: {batch_ratio:.0f}x batch, {time_ratio:.1f}x time"
)
print(f" Linearity factor: {linearity:.2f} (1.0 = perfect linear scaling)")
print(f" TFLOPS range: {tf0:.2f} - {tf_last:.2f}")
# Summary
passed = sum(1 for _, ok, *_ in results if ok)
print("\n" + "=" * 70)
print(f" Results: {passed}/{len(results)} passed")
print(f" Fixed: S={SEQLEN} H={NHEAD} D={HDIM}")
print(f" Sweep: batch={BATCHES}")
print(f" Status: {'PASS' if passed == len(results) else 'FAIL'}")
print("=" * 70)
return 0 if passed == len(results) else 1
if __name__ == "__main__":
sys.exit(main())