Files
composable_kernel/dispatcher/examples/fmha/python/12_masks_fmha.py
Vidyasagar Ananthan b20458e19e [rocm-libraries] ROCm/rocm-libraries#5260 (commit a1834d2)
[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>
2026-05-17 00:29:40 -07:00

240 lines
7.6 KiB
Python

#!/usr/bin/env python3
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT
"""
Example 12: Attention Masks
Demonstrates all 5 mask types supported by the FMHA dispatcher:
1. no_mask (0) -- Full attention, no masking
2. top_left (1) -- Causal mask aligned to top-left corner
3. bottom_right (2) -- Causal mask aligned to bottom-right corner
4. sliding_window -- Local attention within a fixed window
5. generic -- Arbitrary user-defined mask pattern
For each mask type, this example:
- Creates an FmhaProblem
- Attempts GPU execution via prebuilt kernel
- Computes CPU reference with the mask applied
- Validates results
Usage:
python3 12_masks_fmha.py
python3 12_masks_fmha.py --seqlen 256
python3 12_masks_fmha.py --window-size 64
"""
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,
detect_gpu_arch,
setup_fmha_dispatcher,
)
MASK_TYPES = {
"no_mask": 0,
"top_left": 1,
"bottom_right": 2,
"sliding_window": 3,
"generic": 4,
}
def make_causal_mask_top_left(seqlen_q: int, seqlen_k: int) -> np.ndarray:
"""Causal mask aligned to top-left: position i can attend to positions <= i."""
row = np.arange(seqlen_q).reshape(-1, 1)
col = np.arange(seqlen_k).reshape(1, -1)
return (col <= row).astype(np.float32)
def make_causal_mask_bottom_right(seqlen_q: int, seqlen_k: int) -> np.ndarray:
"""Causal mask aligned to bottom-right: accounts for kv longer than q."""
offset = seqlen_k - seqlen_q
row = np.arange(seqlen_q).reshape(-1, 1)
col = np.arange(seqlen_k).reshape(1, -1)
return (col <= row + offset).astype(np.float32)
def make_sliding_window_mask(seqlen_q: int, seqlen_k: int, window: int) -> np.ndarray:
"""Sliding window: each query attends to a local window of keys."""
row = np.arange(seqlen_q).reshape(-1, 1)
col = np.arange(seqlen_k).reshape(1, -1)
offset = seqlen_k - seqlen_q
return ((col <= row + offset) & (col >= row + offset - window + 1)).astype(
np.float32
)
def make_generic_mask(seqlen_q: int, seqlen_k: int) -> np.ndarray:
"""Generic checkerboard mask for demonstration."""
row = np.arange(seqlen_q).reshape(-1, 1)
col = np.arange(seqlen_k).reshape(1, -1)
return ((row + col) % 2 == 0).astype(np.float32)
def cpu_masked_attention(
Q: np.ndarray,
K: np.ndarray,
V: np.ndarray,
scale: float,
mask: np.ndarray,
) -> np.ndarray:
"""CPU reference: scaled dot-product attention with arbitrary mask.
Q: [batch, nhead, seqlen_q, hdim]
mask: [seqlen_q, seqlen_k] (broadcast over batch and head)
"""
S = np.matmul(Q, K.transpose(0, 1, 3, 2)) * scale
mask_broad = mask[np.newaxis, np.newaxis, :, :]
S = np.where(mask_broad > 0, S, -1e9)
S_max = S.max(axis=-1, keepdims=True)
S_exp = np.exp(S - S_max)
P = S_exp / S_exp.sum(axis=-1, keepdims=True)
return np.matmul(P, V)
def main():
parser = argparse.ArgumentParser(description="Attention Masks")
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-q", type=int, default=128)
parser.add_argument("--seqlen-k", type=int, default=128)
parser.add_argument("--hdim", type=int, default=128)
parser.add_argument("--window-size", type=int, default=32)
args = parser.parse_args()
print("=" * 70)
print("Example 12: Attention Masks")
print("=" * 70)
sq, sk = args.seqlen_q, args.seqlen_k
prob = FmhaProblem(
batch=args.batch,
nhead_q=args.nhead,
nhead_k=args.nhead,
seqlen_q=sq,
seqlen_k=sk,
hdim_q=args.hdim,
hdim_v=args.hdim,
)
print(f"\n Problem: B={prob.batch} H={prob.nhead_q} Sq={sq} Sk={sk} D={args.hdim}")
print(f" Window: {args.window_size}")
# --- Generate data ---
np.random.seed(42)
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)
# --- Try GPU runner ---
runner = None
config = FmhaKernelConfig(
data_type="fp16",
hdim_q=args.hdim,
hdim_v=args.hdim,
gfx_arch=args.arch,
)
setup = setup_fmha_dispatcher(config)
if setup.success:
runner = setup.runner
print(f"\n GPU runner loaded (JIT build: {setup.build_time_s:.1f}s)")
else:
print(f"\n GPU runner not available: {setup.error}")
# --- Build masks ---
masks = {
"no_mask": np.ones((sq, sk), dtype=np.float32),
"top_left": make_causal_mask_top_left(sq, sk),
"bottom_right": make_causal_mask_bottom_right(sq, sk),
"sliding_window": make_sliding_window_mask(sq, sk, args.window_size),
"generic": make_generic_mask(sq, sk),
}
validator = FmhaValidator(rtol=1e-2, atol=1e-2)
print(
f"\n {'#':<3} {'MaskType':<18} {'ID':<4} {'Density':>8} {'GPUStatus':<12} {'CPURef':<8} {'MaxErr':>10} {'Status':>8}"
)
print(" " + "-" * 76)
results = []
for i, (name, mask) in enumerate(masks.items(), 1):
mask_id = MASK_TYPES[name]
density = mask.sum() / mask.size * 100
# GPU attempt (prebuilt only supports no_mask)
gpu_status = "N/A"
gpu_out = None
if runner is not None:
res = runner.run(Q_fp16, K_fp16, V_fp16, prob)
if res.success:
gpu_out = res.output
gpu_status = "OK" if name == "no_mask" else "no_mask*"
else:
gpu_status = "unsupported"
# CPU reference with mask
O_ref = cpu_masked_attention(Q_f32, K_f32, V_f32, prob.scale, mask)
cpu_status = "OK"
# Validate
if gpu_out is not None and name == "no_mask":
ok, max_abs, _ = validator.check(gpu_out, O_ref)
tag = "PASS" if ok else "FAIL"
err_str = f"{max_abs:.2e}"
else:
ok = True
tag = "DEMO"
err_str = "---"
print(
f" {i:<3} {name:<18} {mask_id:<4} {density:>7.1f}% {gpu_status:<12} {cpu_status:<8} {err_str:>10} {tag:>8}"
)
results.append((name, ok))
# --- Mask visualization ---
print("\n--- Mask Patterns (first 8x8 corner) ---")
view_size = min(8, sq, sk)
for name, mask in masks.items():
corner = mask[:view_size, :view_size]
print(f"\n {name}:")
for r in range(view_size):
row_str = " ".join(
"" if corner[r, c] > 0 else "·" for c in range(view_size)
)
print(f" {row_str}")
# --- Summary ---
all_ok = all(ok for _, ok in results)
print("\n" + "=" * 70)
print(f" Mask types tested: {len(masks)}")
print(" no_mask: Full attention (all positions visible)")
print(" top_left: Causal from top-left (autoregressive)")
print(" bottom_right: Causal from bottom-right (kv-padded)")
print(f" sliding_window: Local window of {args.window_size} keys")
print(" generic: Arbitrary (checkerboard demo)")
print(" GPU: Prebuilt supports no_mask only")
print(f" Status: {'PASS' if all_ok else 'FAIL'}")
print("=" * 70)
return 0
if __name__ == "__main__":
sys.exit(main())