-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathbench_attention.py
More file actions
179 lines (150 loc) · 5.78 KB
/
Copy pathbench_attention.py
File metadata and controls
179 lines (150 loc) · 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# SPDX-FileCopyrightText: Copyright (c) <2025> NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0
from functools import cache
from math import ceil, sqrt
from itertools import product
import benchmark_tuning
from conftest import dtype_id, shape_id
from torch.nn.functional import scaled_dot_product_attention
from torch.nn.attention import sdpa_kernel, SDPBackend
import cuda.tile as ct
from cuda.tile.tune import exhaustive_search
import pytest
import torch
from util import estimate_bench_iter
from kernels.attention import fmha_kernel
def qkv_id(qkv_shape: tuple[tuple[int, ...], tuple[int, ...]]) -> str:
q_shape, kv_shape = qkv_shape
if q_shape[2] == 1:
prefix = "decode-"
else:
prefix = "prefill-"
b, q_head, q_len, d = q_shape
_, k_head, k_len, _ = kv_shape
return prefix + shape_id((b, q_head, k_head, q_len, k_len, d))
@pytest.fixture(
params=[
# B, H, L, D
((1, 32, 1024, 128), (1, 32, 1024, 128)), # prefill
((1, 32, 1024, 128), (1, 8, 1024, 128)), # prefill + gqa
((1, 32, 8192, 128), (1, 32, 8192, 128)), # prefill
((1, 32, 8192, 128), (1, 8, 8192, 128)), # prefill + gqa
((1, 32, 1, 128), (1, 32, 1024, 128)), # decode
((8, 32, 1, 128), (8, 32, 1024, 128)), # decode
((1, 32, 1, 128), (1, 8, 1024, 128)), # decode + gqa
((8, 32, 1, 128), (8, 8, 1024, 128)), # decode + gqa
],
ids=qkv_id)
def qkv_shape(request):
return request.param
@pytest.fixture(params=[torch.float16, torch.bfloat16], ids=dtype_id)
def dtype(request):
return request.param
@pytest.mark.benchmark(group='attention')
def bench_fmha(qkv_shape, dtype, backend, benchmark):
q_shape, kv_shape = qkv_shape
q = torch.randn(q_shape, dtype=dtype, device='cuda:0')
k = torch.randn(kv_shape, dtype=dtype, device='cuda:0')
v = torch.randn(kv_shape, dtype=dtype, device='cuda:0')
o = torch.empty_like(q)
ref = torch.empty_like(q)
is_causal = q_shape[2] == kv_shape[2]
enable_gqa = q_shape[1] != kv_shape[1]
backend(q, k, v, o, is_causal, enable_gqa)
ref_fmha(q, k, v, ref, is_causal, enable_gqa)
torch.testing.assert_close(o, ref, atol=1e-2, rtol=5e-2)
torch.cuda.synchronize()
warmup_rounds, iterations, rounds = estimate_bench_iter(
backend, (q, k, v, o, is_causal, enable_gqa),
cudagraph=True
)
benchmark.pedantic(
backend, (q, k, v, o, is_causal, enable_gqa),
rounds=rounds, warmup_rounds=warmup_rounds, iterations=iterations,
cudagraph=True
)
B, H, L, D = q.shape
# first gemm mma(q, k): 2 * B * H * L * L * D
# second gemm mma(p, v): 2 * B * H * L * L * D
flop_count = 4 * B * H * L * L * D
if is_causal:
flop_count /= 2
bytes_rw = sum([t.numel() * t.dtype.itemsize for t in (q, k, v, o)])
benchmark.extra_info['flop_count'] = flop_count
benchmark.extra_info['bytes_rw'] = bytes_rw
def cutile_fmha(q, k, v, o, is_causal, enable_gqa):
b, qh, q_len, d = q.shape
_, kh, k_len, _ = k.shape
qk_scale = 1 / sqrt(d)
cfg = benchmark_tuning.get_tuned_config(tune_fmha, is_causal=is_causal)
TILE_M, TILE_N = cfg["tile_m"], cfg["tile_n"]
query_group_size = qh // kh
grid = (ceil(q_len / TILE_M), b * qh, 1)
input_pos = 0 if q_len == k_len else (k_len - 1)
EVEN_K = (k_len % TILE_N) == 0
kernel = _fmha_kernel(cfg["occupancy"])
ct.launch(torch.cuda.current_stream(), grid, kernel,
(q, k, v, o,
qk_scale,
input_pos,
d, qh,
TILE_M, TILE_N,
query_group_size, is_causal, EVEN_K))
@cache
def _fmha_kernel(occupancy):
return fmha_kernel.replace_hints(occupancy=occupancy)
@pytest.mark.parametrize("is_causal", [False, True])
def tune_fmha(is_causal):
if is_causal:
q_shape, kv_shape = (1, 32, 8192, 128), (1, 32, 8192, 128)
else:
q_shape, kv_shape = (1, 32, 1, 128), (1, 32, 1024, 128)
dtype = torch.float16
q = torch.randn(q_shape, dtype=dtype, device='cuda:0')
k = torch.randn(kv_shape, dtype=dtype, device='cuda:0')
v = torch.randn(kv_shape, dtype=dtype, device='cuda:0')
o = torch.empty_like(q)
b, qh, q_len, d = q.shape
_, kh, k_len, _ = k.shape
qk_scale = 1 / sqrt(d)
query_group_size = qh // kh
input_pos = 0 if q_len == k_len else (k_len - 1)
search_space = [
{"tile_m": tile_m, "tile_n": tile_n, "occupancy": occupancy}
for tile_m, tile_n, occupancy in product(
(64, 128, 256),
(64, 128, 256),
(1, 2, 4),
)
]
return exhaustive_search(
search_space,
torch.cuda.current_stream(),
grid_fn=lambda cfg: (ceil(q_len / cfg["tile_m"]), b * qh, 1),
kernel=fmha_kernel,
args_fn=lambda cfg: (
q, k, v, o,
qk_scale,
input_pos,
d, qh,
cfg["tile_m"], cfg["tile_n"],
query_group_size, is_causal, (k_len % cfg["tile_n"]) == 0,
),
hints_fn=lambda cfg: {"occupancy": cfg["occupancy"]},
)
def torch_fmha(q, k, v, o, is_causal, enable_gqa):
backend = SDPBackend.CUDNN_ATTENTION \
if (q.shape[2] == k.shape[2]) \
else SDPBackend.FLASH_ATTENTION
with sdpa_kernel(backend):
ret = scaled_dot_product_attention(q, k, v,
is_causal=is_causal,
enable_gqa=enable_gqa)
o.copy_(ret)
def ref_fmha(q, k, v, o, is_causal, enable_gqa):
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
ret = scaled_dot_product_attention(q, k, v,
is_causal=is_causal,
enable_gqa=enable_gqa)
o.copy_(ret)