Skip to content

Commit e1c8124

Browse files
committed
add linalg to xegpu fused attention example
1 parent b4ed8b4 commit e1c8124

7 files changed

Lines changed: 1523 additions & 1 deletion

File tree

‎examples/xegpu/fused_attention.py‎

Lines changed: 387 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,387 @@
1+
# RUN: %PYTHON %s --dump-kernel=xegpu-wg | FileCheck %s
2+
# CHECK: module attributes {gpu.container_module} {
3+
4+
"""
5+
XeGPU fused attention benchmark.
6+
"""
7+
8+
import argparse
9+
from typing import Optional
10+
from functools import cached_property
11+
12+
import numpy as np
13+
from mlir import ir
14+
15+
from lighthouse import dialects as lh_dialects
16+
from lighthouse.execution.runner import Runner
17+
from lighthouse.pipeline.driver import TransformDriver
18+
from lighthouse.execution import GPUMemoryManager
19+
from lighthouse.utils.numpy import mlir_to_numpy_dtype
20+
from lighthouse.ingress.mlir_gen import get_mlir_elem_type
21+
from lighthouse.ingress.mlir_gen.gpu_fused_attention_payload import (
22+
generate_gpu_fused_attention_payload,
23+
)
24+
from lighthouse.schedule.xegpu import fused_attention_schedule, xegpu_to_binary
25+
26+
27+
def fused_attention_complexity(Z: int, H: int, n_ctx: int, n_head: int, nbytes: int):
28+
"""
29+
Complexity of fused attention operation.
30+
31+
For each batch and head:
32+
- Q @ K^T: O(n_ctx^2 * n_head) operations
33+
- Softmax: O(n_ctx^2) operations
34+
- Attention @ V: O(n_ctx^2 * n_head) operations
35+
Total: approximately 2*n_ctx^2*n_head FLOPs per batch and head
36+
"""
37+
# Approximation: 2 * n_ctx^2 * n_head FLOPs per batch and head
38+
flop_count = Z * H * 2 * n_ctx * n_ctx * n_head
39+
# Memory: read Q, K, V and write output
40+
memory_reads = 3 * Z * H * n_ctx * n_head * nbytes
41+
memory_writes = Z * H * n_ctx * n_head * nbytes
42+
return flop_count, memory_reads, memory_writes
43+
44+
45+
def check_correctness(
46+
Q: np.ndarray,
47+
K: np.ndarray,
48+
V: np.ndarray,
49+
output_arr: np.ndarray,
50+
verbose: int = 0,
51+
) -> bool:
52+
"""
53+
Check correctness of fused attention output.
54+
55+
Reference implementation:
56+
- scores = Q @ K^T / sqrt(n_head)
57+
- attention_weights = softmax(scores, dim=-1)
58+
- output = attention_weights @ V
59+
"""
60+
# Use float32 for computation
61+
Q_f32 = Q.astype(np.float32)
62+
K_f32 = K.astype(np.float32)
63+
V_f32 = V.astype(np.float32)
64+
65+
Z, H, n_ctx, n_head = Q.shape
66+
scale = 1.0 / np.sqrt(n_head)
67+
68+
output_ref = np.zeros_like(Q_f32)
69+
70+
# Compute reference for each batch and head
71+
for z in range(Z):
72+
for h in range(H):
73+
# scores = Q @ K^T / sqrt(n_head)
74+
scores = Q_f32[z, h] @ K_f32[z, h].T * scale
75+
76+
# softmax along last dimension
77+
max_vals = np.max(scores, axis=1, keepdims=True)
78+
exp_vals = np.exp(scores - max_vals)
79+
sum_vals = np.sum(exp_vals, axis=1, keepdims=True)
80+
attention_weights = exp_vals / sum_vals
81+
82+
# output = attention_weights @ V
83+
output_ref[z, h] = attention_weights @ V_f32[z, h]
84+
85+
output = output_arr.astype(np.float32)
86+
87+
if verbose > 1:
88+
print("Reference solution (first batch, first head, first 5 rows):")
89+
print(output_ref[0, 0, :5])
90+
print("Computed solution (first batch, first head, first 5 rows):")
91+
print(output[0, 0, :5])
92+
93+
# Check values match reference
94+
values_ok = np.allclose(output, output_ref, rtol=1e-3, atol=1e-3)
95+
success = values_ok
96+
97+
if verbose:
98+
if success:
99+
print("PASSED")
100+
else:
101+
print("FAILED!")
102+
if not values_ok:
103+
max_diff = np.abs(output - output_ref).max()
104+
print(f" Values mismatch. Max abs diff: {max_diff:.6e}")
105+
return success
106+
107+
108+
class XeGPUFusedAttention:
109+
"""
110+
Fused attention workload on XeGPU.
111+
112+
Computes fused attention:
113+
output = softmax(Q @ K^T / sqrt(n_head)) @ V
114+
115+
All Q, K, V matrices have shape (Z, H, n_ctx, n_head) where:
116+
- Z: batch size
117+
- H: number of heads
118+
- n_ctx: context length
119+
- n_head: head dimension
120+
"""
121+
122+
def __init__(
123+
self,
124+
Z: int,
125+
H: int,
126+
n_ctx: int,
127+
n_head: int,
128+
dtype: str = "f16",
129+
):
130+
self.Z = Z
131+
self.H = H
132+
self.n_ctx = n_ctx
133+
self.n_head = n_head
134+
self.shape = (Z, H, n_ctx, n_head)
135+
assert dtype == "f16", "Only f16 type is supported for fused attention"
136+
self.elem_type = get_mlir_elem_type(dtype)
137+
self.dtype = mlir_to_numpy_dtype(self.elem_type)
138+
self.memory_manager_class = GPUMemoryManager
139+
self.payload_function_name = "payload"
140+
141+
@cached_property
142+
def _initial_host_arrays(self) -> tuple[np.ndarray]:
143+
"""Generate initial values on host with numpy."""
144+
np.random.seed(42)
145+
# Initialize Q, K, V with small random values
146+
Q = np.random.uniform(-0.5, 0.5, self.shape).astype(self.dtype)
147+
K = np.random.uniform(-0.5, 0.5, self.shape).astype(self.dtype)
148+
V = np.random.uniform(-0.5, 0.5, self.shape).astype(self.dtype)
149+
output_arr = np.zeros(self.shape, dtype=self.dtype)
150+
return (output_arr, Q, K, V)
151+
152+
def get_complexity(self) -> tuple[int, int, int]:
153+
nbytes = np.dtype(self.dtype).itemsize
154+
return fused_attention_complexity(
155+
self.Z, self.H, self.n_ctx, self.n_head, nbytes
156+
)
157+
158+
def payload_module(self) -> ir.Module:
159+
"""Generate MLIR module for fused attention payload."""
160+
return generate_gpu_fused_attention_payload(
161+
func_name=self.payload_function_name,
162+
Z=self.Z,
163+
H=self.H,
164+
n_ctx=self.n_ctx,
165+
n_head=self.n_head,
166+
dtype=self.elem_type,
167+
)
168+
169+
def schedule_modules(
170+
self, stop_at_stage: Optional[str] = None, parameters: Optional[dict] = None
171+
) -> list[ir.Module]:
172+
"""Generate transform schedule for fused attention."""
173+
schedules = []
174+
schedules.append(Runner.get_bench_wrapper_schedule(self.payload_function_name))
175+
176+
schedules.append(
177+
fused_attention_schedule(
178+
stop_at_stage=stop_at_stage,
179+
parameters=parameters,
180+
)
181+
)
182+
183+
if stop_at_stage and stop_at_stage != "final":
184+
return schedules
185+
186+
schedules.append(xegpu_to_binary())
187+
188+
return schedules
189+
190+
def shared_libs(self) -> list[str]:
191+
return ["libmlir_levelzero_runtime.so"]
192+
193+
194+
def parse_cli():
195+
parser = argparse.ArgumentParser(
196+
description="Fused Attention using MLIR XeGPU",
197+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
198+
)
199+
parser.add_argument(
200+
"--batch-size",
201+
type=int,
202+
default=2,
203+
help="Batch size (Z)",
204+
)
205+
parser.add_argument(
206+
"--num-heads",
207+
type=int,
208+
default=8,
209+
help="Number of attention heads (H)",
210+
)
211+
parser.add_argument(
212+
"--n-ctx",
213+
type=int,
214+
default=4096,
215+
help="Context length (sequence length)",
216+
)
217+
parser.add_argument(
218+
"--n-head",
219+
type=int,
220+
default=64,
221+
help="Head dimension",
222+
)
223+
parser.add_argument(
224+
"--wg-rows",
225+
type=int,
226+
default=128,
227+
help="Number of Q*K^T*V rows computed by each work group",
228+
)
229+
parser.add_argument(
230+
"--sg-rows",
231+
type=int,
232+
default=16,
233+
help="Number of Q*K^T*V rows computed by each subgroup",
234+
)
235+
parser.add_argument(
236+
"--subgroup-size",
237+
type=int,
238+
default=16,
239+
help="Subgroup size",
240+
)
241+
parser.add_argument(
242+
"--inner-loop-tile-size",
243+
type=int,
244+
default=64,
245+
help="Tile size for the inner reduction dimension (K/V sequence length)",
246+
)
247+
parser.add_argument(
248+
"--nruns",
249+
type=int,
250+
default=1000,
251+
help="Number of runs to average the execution time.",
252+
)
253+
parser.add_argument(
254+
"--nwarmup",
255+
type=int,
256+
default=20,
257+
help="Number of warm-up iterations before benchmarking.",
258+
)
259+
parser.add_argument(
260+
"--check-result",
261+
action="store_true",
262+
help="Check the result of the fused attention computation.",
263+
)
264+
parser.add_argument(
265+
"--dump-kernel",
266+
type=str,
267+
choices=[
268+
"initial",
269+
"outer-tiled",
270+
"inner-tiled",
271+
"vectorized",
272+
"bufferized",
273+
"gpu-outlining",
274+
"xegpu-initial",
275+
"xegpu-wg",
276+
"final",
277+
],
278+
help="Dump kernel IR at different stages of lowering and exit without "
279+
"executing the kernel.",
280+
)
281+
parser.add_argument(
282+
"--dump-schedule",
283+
action="store_true",
284+
help="Dump transform schedule.",
285+
)
286+
parser.add_argument(
287+
"--verbose",
288+
"-v",
289+
action="count",
290+
default=0,
291+
help="Increase output verbosity (e.g. print reference and computed solutions).",
292+
)
293+
args = parser.parse_args()
294+
return args
295+
296+
297+
if __name__ == "__main__":
298+
args = parse_cli()
299+
300+
params = {
301+
"batch_size": args.batch_size,
302+
"num_heads": args.num_heads,
303+
"n_ctx": args.n_ctx,
304+
"n_head": args.n_head,
305+
"wg_rows": args.wg_rows,
306+
"sg_rows": args.sg_rows,
307+
"subgroup_size": args.subgroup_size,
308+
"inner_loop_tile_size": args.inner_loop_tile_size,
309+
}
310+
311+
Z = args.batch_size
312+
H = args.num_heads
313+
n_ctx = args.n_ctx
314+
n_head = args.n_head
315+
dtype = "f16"
316+
317+
with ir.Context(), ir.Location.unknown():
318+
lh_dialects.register_and_load()
319+
wload = XeGPUFusedAttention(Z=Z, H=H, n_ctx=n_ctx, n_head=n_head, dtype=dtype)
320+
321+
if args.dump_kernel or args.dump_schedule:
322+
pipeline = TransformDriver(
323+
wload.schedule_modules(
324+
stop_at_stage=args.dump_kernel, parameters=params
325+
)
326+
)
327+
payload = pipeline.apply(wload.payload_module())
328+
if args.dump_kernel:
329+
print(payload)
330+
if args.dump_schedule:
331+
for schedule_module in wload.schedule_modules(parameters=params):
332+
print(schedule_module)
333+
else:
334+
pipeline = TransformDriver(wload.schedule_modules(parameters=params))
335+
payload = pipeline.apply(wload.payload_module())
336+
runner = Runner(
337+
payload,
338+
mem_manager_cls=wload.memory_manager_class,
339+
shared_libs=wload.shared_libs(),
340+
)
341+
if args.check_result:
342+
# Setup callback function to copy result from device to host.
343+
result_host_copy = np.zeros(wload.shape, dtype=wload.dtype)
344+
argument_access_callback = Runner.get_gpu_argument_access_callback(
345+
result_host_copy, arg_index=0
346+
)
347+
348+
# Execute kernel once.
349+
runner.execute(
350+
host_input_buffers=wload._initial_host_arrays,
351+
payload_function_name=wload.payload_function_name,
352+
argument_access_callback=argument_access_callback,
353+
)
354+
355+
# Compute reference solution on host.
356+
Q, K, V = wload._initial_host_arrays[1:4]
357+
success = check_correctness(
358+
Q,
359+
K,
360+
V,
361+
result_host_copy,
362+
verbose=args.verbose,
363+
)
364+
if not success:
365+
raise ValueError("Result mismatch!")
366+
else:
367+
print("Result is correct. Proceeding to benchmark...")
368+
369+
times = runner.benchmark(
370+
host_input_buffers=wload._initial_host_arrays,
371+
nruns=args.nruns,
372+
nwarmup=args.nwarmup,
373+
)
374+
times *= 1e6 # convert to microseconds
375+
elapsed = np.mean(times)
376+
flop_count = wload.get_complexity()[0]
377+
gflops = flop_count / (elapsed * 1e-6) / 1e9
378+
379+
print(
380+
f"batch-size={Z} "
381+
f"num-heads={H} "
382+
f"n-ctx={n_ctx} "
383+
f"n-head={n_head} "
384+
f"dt={dtype} "
385+
f"time(us): {elapsed:.2f} "
386+
f"GFLOPS: {gflops:.2f} "
387+
)

0 commit comments

Comments
 (0)