forked from umiswing/test_flashmask
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark_blockmask.py
More file actions
227 lines (185 loc) · 8.13 KB
/
benchmark_blockmask.py
File metadata and controls
227 lines (185 loc) · 8.13 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import os
import numpy as np
from functools import lru_cache
from typing import Optional, List
import random
from block_sparse_attn import (
block_sparse_attn_func,
flash_attn_varlen_func,
)
import torch
import torch.nn.functional as F
from tabulate import tabulate
from triton.testing import do_bench
torch.set_default_device("cuda")
torch.manual_seed(0)
np.random.seed(0)
random.seed(0)
torch._dynamo.config.cache_size_limit = 1000
@lru_cache
def create_block_mask_cached(score_mod, B, H, M, N, device="cuda"):
block_mask = create_block_mask(score_mod, B, H, M, N, device=device, _compile=True, BLOCK_SIZE=[128, 128])
return block_mask
def calculate_tflops(flops: float, time_ms: float, multiplier: int) -> float:
return multiplier * flops * (1e3 / time_ms) / 1e12
def cal_flops(B, H, Sq, Sk, D, mode='fwd',causal=False):
assert mode in ["fwd", "bwd", "fwd_bwd"]
f = 4 * B * Sq * Sk * H * D
if(causal):
f *= 0.5
return f if mode == "fwd" else (2.5 * f if mode == "bwd" else 3.5 * f)
def cal_tflops(flops, time_ms):
return flops * (1e3 / time_ms) / 1e12
def print_header(text):
width = 91
print("╔" + "═" * (width - 2) + "╗")
print(f"║ {text.center(width - 4)} ║")
print("╚" + "═" * (width - 2) + "╝")
def test_block_mask(
B: int = 16,
H: int = 16,
S: int = 8192,
D: int = 64,
dtype = 'bf16',
skip_correctness: bool = False,
print_mask: bool = True,
device: str = "cuda",
causal: bool = False,
sparsity: float = 0.0,
):
if dtype == 'bfloat16':
data_type = torch.bfloat16
else:
data_type = torch.float16
seqlen = S
batch_size = B
nheads = H
headdim = D
dropout_p = 0.0
shape = (batch_size * seqlen, nheads, headdim)
q = torch.randn(shape, device=device, dtype=data_type, requires_grad=True)
k = torch.randn(shape, device=device, dtype=data_type, requires_grad=True)
v = torch.randn(shape, device=device, dtype=data_type, requires_grad=True)
gradOut = torch.randn(shape, device=device, dtype=data_type)
block_attention_call = lambda: flex_attention(*qkv, score_mod=score_mod, block_mask=block_mask)
cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32, device=device)
head_mask_type = torch.tensor([1] * nheads, device=device, dtype=torch.int32)
base_blockmask, real_sparsity = generate_base_sparsity_mask(seqlen, seqlen, block_size, block_size, block_size, sparsity, causal = causal, device=device)
base_blockmask = base_blockmask.unsqueeze(0).repeat(batch_size, nheads, 1, 1)
block_attention_call = lambda: block_sparse_attn_func(q, k, v, cu_seqlens, cu_seqlens, head_mask_type, None, base_blockmask, seqlen, seqlen, dropout_p, is_causal=causal, exact_streaming=False)
# Forward pass
fwd_time_ms = do_bench(block_attention_call)
# torch._functorch.config.donated_buffer=False
# Backward pass
block_out = block_attention_call()
bwd_time_ms = do_bench(lambda: block_out.backward(gradOut, retain_graph=True))
total_time_ms = fwd_time_ms + bwd_time_ms
density = 1 - real_sparsity
fwd_flops = density * cal_flops(B, H, S, S, D, mode='fwd', causal = causal)
bwd_flops = density * cal_flops(B, H, S, S, D, mode='bwd', causal = causal)
total_flops = density * cal_flops(B, H, S, S, D, mode='fwd_bwd', causal = causal)
fwd_tflops = cal_tflops(fwd_flops, fwd_time_ms)
bwd_tflops = cal_tflops(bwd_flops, bwd_time_ms)
total_tflops = cal_tflops(total_flops, total_time_ms)
return fwd_time_ms, bwd_time_ms, total_time_ms, fwd_flops, bwd_flops, total_flops, fwd_tflops, bwd_tflops, total_tflops, real_sparsity
def generate_base_sparsity_mask(max_seqlen_q, max_seqlen_k, round_base, m_block_dim, n_block_dim, sparsity, causal=False, device="cuda"):
def round_to_multiple(x, base):
return ((x + base - 1) // base) * base
nrow, ncol = round_to_multiple(max_seqlen_q, round_base) // m_block_dim, round_to_multiple(max_seqlen_k, round_base) // n_block_dim
base_mask = torch.zeros(1, nrow, ncol, device=device, dtype=torch.bool)
total_block_num = 0
density = 1.0 - sparsity
if not density == 0.0 and not density == 1.0:
for i in range(nrow): # do in reverse order
idx = nrow - i - 1
if causal:
available_col_num = max(0, ncol - i)
total_block_num += available_col_num
num_one = max(1, int(density * available_col_num))
base_mask[0][idx, torch.randperm(available_col_num)[:num_one]] = True
else:
available_col_num = ncol
total_block_num += available_col_num
num_one = max(1, int(density * available_col_num))
base_mask[0][idx, torch.randperm(available_col_num)[:num_one]] = True
elif density == 1.0:
base_mask[0] = torch.ones_like(base_mask[0])
total_block_num = nrow * ncol
else:
total_block_num = nrow * ncol
calculated_block_num = base_mask.sum().item()
real_sparsity = 1.0 - calculated_block_num / total_block_num
return base_mask, real_sparsity
block_size = 128
def get_sparsity_list(sampling_steps, seqlen, causal):
blockmask_element_num = (seqlen // block_size) ** 2 // (2 if causal else 1)
stride = max(blockmask_element_num // sampling_steps, 1)
actual_steps = (blockmask_element_num + stride - 1) // stride
sparsity_list = []
for i in range(actual_steps):
sparse_rate = (1 + i * stride) / blockmask_element_num
if sparse_rate > 0.95 or sparse_rate < 0.0:
continue
sparsity_list.append(sparse_rate)
return sparsity_list
def main():
"""Run the benchmark with the given examples.
Args:
examples: List of examples to run. If "all" is specified, all examples will be run.
"""
repeats = 15
block_sparse_repeats = 3
device = 'cuda:0'
dtype = 'bfloat16'
causal = True
batch_size = 1
sparsity_sampling_steps = 5
seqlen_vals = [1024,2048,4096,8192,16384,32768,65536,65536 * 2]
headdim = 128
dim = 4096
dropout_p = 0.0
all_results = {}
for seqlen in seqlen_vals:
results = []
sparsity_list = get_sparsity_list(sparsity_sampling_steps, seqlen, causal)
print(f"sparsity_list: {sparsity_list}")
for causal in [True, False]:
for sparsity in sparsity_list:
tmp_results = []
sum_sparsity, sum_speed, sum_latency = 0, 0, 0
for _ in range(block_sparse_repeats):
fw_time, bw_time, total_time, fw_flops, bw_flops, total_flops, fw_tflops, bw_tflops, total_tflops, sparsity = test_block_mask(B=batch_size, H=dim // headdim, S=seqlen, D=headdim, dtype=dtype, skip_correctness=True, print_mask=False, device=device, causal=causal,sparsity=sparsity)
tmp_results.append([f"{fw_time:.4f}", f"{bw_time:.4f}", f"{total_time:.4f}", f"{fw_flops:.4f}", f"{bw_flops:.4f}", f"{total_flops:.4f}", f"{fw_tflops:.4f}", f"{bw_tflops:.4f}", f"{total_tflops:4f}", f"{sparsity:.4f}"])
tmp_array = np.array(tmp_results).astype(float)
# print(tmp_array)
avg_vals = tmp_array.mean(axis=0)
results.append([causal] + avg_vals.tolist())
headers = [
"Causal",
"FW Time (ms)",
"BW Time (ms)",
"TOTAL Time (ms)",
"FW FLOPs",
"BW FLOPs",
"TOTAL FLOPs",
"FW TFLOPs/s",
"BW TFLOPs/s",
"TOTAL TFLOPs/s",
"Sparsity",
]
print(results)
print(
tabulate(
results,
headers=headers,
tablefmt="grid",
)
)
content2=tabulate(results, headers=headers, tablefmt="tsv")
print(content2)
os.makedirs(f"{dtype}", exist_ok=True)
text_file = open(f"{dtype}/blockattention_{batch_size}_{seqlen}_{dim // headdim}_{headdim}.csv","w")
text_file.write(content2)
text_file.close()
if __name__ == "__main__":
main()