mirror of
https://github.com/ROCm/composable_kernel.git
synced 2026-06-29 19:28:33 +00:00
[CK] [CK_Tile] Add FMHA scaffolding to CK kernel dispatcher (#5260) ## 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. --------- Co-authored-by: Yaswanth Raparti <113389104+yraparti@users.noreply.github.com> Co-authored-by: Mohsen Saffari <mohsen.saffari@amd.com> Co-authored-by: Maksim (Max) Podkorytov <Maksim.Podkorytov@amd.com> Co-authored-by: yashagar <yashagar@amd.com>
246 lines
7.4 KiB
Python
246 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
"""
|
|
Example 14: Attention Dropout with LSE
|
|
|
|
Demonstrates:
|
|
1. Dropout applied to attention probabilities
|
|
2. Log-sum-exp (LSE) storage for numerical stability
|
|
3. Statistical validation (dropout is stochastic)
|
|
4. Reproducibility with seed control
|
|
|
|
Dropout zeros out attention weights with probability p_drop, then scales
|
|
remaining weights by 1/(1-p_drop) to preserve expected value.
|
|
LSE stores log(sum(exp(scores))) per query position for backward pass.
|
|
|
|
Usage:
|
|
python3 14_dropout_fmha.py
|
|
python3 14_dropout_fmha.py --p-drop 0.3
|
|
python3 14_dropout_fmha.py --seqlen 256 --seed 123
|
|
"""
|
|
|
|
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 (
|
|
FmhaProblem,
|
|
FmhaKernelConfig,
|
|
FmhaValidator,
|
|
cpu_attention_fwd,
|
|
detect_gpu_arch,
|
|
setup_fmha_dispatcher,
|
|
)
|
|
|
|
|
|
def cpu_attention_with_dropout(
|
|
Q: np.ndarray,
|
|
K: np.ndarray,
|
|
V: np.ndarray,
|
|
scale: float,
|
|
p_drop: float,
|
|
seed: int,
|
|
) -> tuple:
|
|
"""CPU reference: attention with dropout and LSE output.
|
|
|
|
Returns:
|
|
(O, P_dropped, lse)
|
|
O: [batch, nhead, seqlen_q, hdim_v]
|
|
P_dropped: [batch, nhead, seqlen_q, seqlen_k] attention weights after dropout
|
|
lse: [batch, nhead, seqlen_q] log-sum-exp of scores
|
|
"""
|
|
S = np.matmul(Q, K.transpose(0, 1, 3, 2)) * scale
|
|
S_max = S.max(axis=-1, keepdims=True)
|
|
S_exp = np.exp(S - S_max)
|
|
S_sum = S_exp.sum(axis=-1, keepdims=True)
|
|
P = S_exp / S_sum
|
|
|
|
lse = (np.log(S_sum.squeeze(-1)) + S_max.squeeze(-1)).astype(np.float32)
|
|
|
|
rng = np.random.RandomState(seed)
|
|
drop_mask = (rng.rand(*P.shape) >= p_drop).astype(np.float32)
|
|
scale_factor = 1.0 / (1.0 - p_drop) if p_drop < 1.0 else 0.0
|
|
P_dropped = P * drop_mask * scale_factor
|
|
|
|
out = np.matmul(P_dropped, V)
|
|
return out, P_dropped, lse
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Attention Dropout with LSE")
|
|
parser.add_argument("--arch", default=detect_gpu_arch())
|
|
parser.add_argument("--batch", type=int, default=2)
|
|
parser.add_argument("--nhead", type=int, default=8)
|
|
parser.add_argument("--seqlen", type=int, default=128)
|
|
parser.add_argument("--hdim", type=int, default=128)
|
|
parser.add_argument("--p-drop", type=float, default=0.2)
|
|
parser.add_argument("--seed", type=int, default=42)
|
|
args = parser.parse_args()
|
|
|
|
print("=" * 70)
|
|
print("Example 14: Attention Dropout with LSE")
|
|
print("=" * 70)
|
|
|
|
prob = FmhaProblem(
|
|
batch=args.batch,
|
|
nhead_q=args.nhead,
|
|
nhead_k=args.nhead,
|
|
seqlen_q=args.seqlen,
|
|
seqlen_k=args.seqlen,
|
|
hdim_q=args.hdim,
|
|
hdim_v=args.hdim,
|
|
)
|
|
|
|
print(
|
|
f"\n Problem: B={prob.batch} H={prob.nhead_q} S={args.seqlen} D={args.hdim}"
|
|
)
|
|
print(f" p_drop: {args.p_drop}")
|
|
print(f" Seed: {args.seed}")
|
|
print(f" LSE shape: [{prob.batch}, {prob.nhead_q}, {prob.seqlen_q}]")
|
|
|
|
# --- Generate data ---
|
|
np.random.seed(args.seed)
|
|
Q_f32 = (np.random.randn(*prob.q_shape()) * 0.1).astype(np.float32)
|
|
K_f32 = (np.random.randn(*prob.k_shape()) * 0.1).astype(np.float32)
|
|
V_f32 = (np.random.randn(*prob.v_shape()) * 0.1).astype(np.float32)
|
|
Q_fp16 = Q_f32.astype(np.float16)
|
|
K_fp16 = K_f32.astype(np.float16)
|
|
V_fp16 = V_f32.astype(np.float16)
|
|
|
|
# --- GPU execution attempt ---
|
|
print("\n--- GPU Execution ---")
|
|
gpu_output = None
|
|
config = FmhaKernelConfig(
|
|
data_type="fp16",
|
|
hdim_q=args.hdim,
|
|
hdim_v=args.hdim,
|
|
gfx_arch=args.arch,
|
|
)
|
|
setup = setup_fmha_dispatcher(config)
|
|
if not setup.success:
|
|
print(f" JIT build failed: {setup.error}")
|
|
else:
|
|
runner = setup.runner
|
|
print(f" JIT build: {setup.build_time_s:.1f}s")
|
|
res = runner.run(Q_fp16, K_fp16, V_fp16, prob)
|
|
if res.success:
|
|
gpu_output = res.output
|
|
print(f" GPU (no dropout): {res.time_ms:.4f} ms, {res.tflops:.2f} TFLOPS")
|
|
print(" Note: JIT kernel runs without dropout; shown for baseline")
|
|
else:
|
|
print(" GPU: Kernel returned failure")
|
|
|
|
# --- CPU reference: no dropout (baseline) ---
|
|
print("\n--- CPU Reference ---")
|
|
O_no_drop = cpu_attention_fwd(Q_f32, K_f32, V_f32, prob.scale)
|
|
|
|
# --- CPU reference: with dropout ---
|
|
drop_rates = [0.0, 0.1, args.p_drop, 0.5]
|
|
|
|
print(
|
|
f"\n {'p_drop':>8} {'OutMean':>10} {'OutStd':>10} {'MaxDiff':>10} {'DropFrac':>10}"
|
|
)
|
|
print(" " + "-" * 52)
|
|
|
|
for p in drop_rates:
|
|
O_drop, P_dropped, lse = cpu_attention_with_dropout(
|
|
Q_f32,
|
|
K_f32,
|
|
V_f32,
|
|
prob.scale,
|
|
p,
|
|
args.seed,
|
|
)
|
|
|
|
total_weights = P_dropped.size
|
|
zeros = (P_dropped == 0).sum()
|
|
actual_drop_frac = zeros / total_weights
|
|
|
|
diff = float(np.abs(O_drop - O_no_drop).max())
|
|
print(
|
|
f" {p:>8.2f} {O_drop.mean():>10.4f} {O_drop.std():>10.4f} "
|
|
f"{diff:>10.2e} {actual_drop_frac:>10.2%}"
|
|
)
|
|
|
|
# --- LSE analysis ---
|
|
print("\n--- LSE (Log-Sum-Exp) Analysis ---")
|
|
_, _, lse = cpu_attention_with_dropout(
|
|
Q_f32,
|
|
K_f32,
|
|
V_f32,
|
|
prob.scale,
|
|
args.p_drop,
|
|
args.seed,
|
|
)
|
|
print(f" LSE shape: {lse.shape}")
|
|
print(f" LSE range: [{lse.min():.4f}, {lse.max():.4f}]")
|
|
print(f" LSE mean: {lse.mean():.4f}")
|
|
print(" LSE is independent of dropout (computed from raw scores)")
|
|
|
|
lse_nodrop = cpu_attention_with_dropout(
|
|
Q_f32,
|
|
K_f32,
|
|
V_f32,
|
|
prob.scale,
|
|
0.0,
|
|
args.seed,
|
|
)[2]
|
|
lse_diff = float(np.abs(lse - lse_nodrop).max())
|
|
print(f" LSE diff (drop vs no-drop): {lse_diff:.2e} (should be 0)")
|
|
|
|
# --- Statistical validation ---
|
|
print("\n--- Statistical Validation ---")
|
|
n_trials = 5
|
|
outputs = []
|
|
for trial in range(n_trials):
|
|
O_t, _, _ = cpu_attention_with_dropout(
|
|
Q_f32,
|
|
K_f32,
|
|
V_f32,
|
|
prob.scale,
|
|
args.p_drop,
|
|
args.seed + trial,
|
|
)
|
|
outputs.append(O_t)
|
|
|
|
O_mean = np.mean(outputs, axis=0)
|
|
O_std = np.std(outputs, axis=0)
|
|
|
|
mean_diff = float(np.abs(O_mean - O_no_drop).max())
|
|
max_std = float(O_std.max())
|
|
|
|
print(f" Trials: {n_trials}")
|
|
print(f" Mean vs no-drop: {mean_diff:.4e} (should be small)")
|
|
print(f" Max output stddev: {max_std:.4e}")
|
|
print(" E[dropout(P)] = P (unbiased estimator)")
|
|
|
|
if gpu_output is not None:
|
|
validator = FmhaValidator(rtol=1e-2, atol=1e-2)
|
|
ok, max_abs, _ = validator.check(gpu_output, O_no_drop)
|
|
print(
|
|
f"\n GPU vs CPU (no-drop): max_err={max_abs:.2e}, {'PASS' if ok else 'FAIL'}"
|
|
)
|
|
|
|
# --- Summary ---
|
|
print("\n" + "=" * 70)
|
|
print(f" Dropout: p_drop={args.p_drop}, seed={args.seed}")
|
|
print(
|
|
f" LSE: Stored for backward pass (shape [{prob.batch},{prob.nhead_q},{prob.seqlen_q}])"
|
|
)
|
|
print(" Key: Dropout is stochastic; validate statistically, not exactly")
|
|
print(" GPU: Prebuilt kernel does not support dropout")
|
|
print(" Status: DEMO")
|
|
print("=" * 70)
|
|
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|