|
| 1 | +""" |
| 2 | +Single-file FlashAttention2 with attention sinks benchmarks. |
| 3 | +
|
| 4 | +Usage: |
| 5 | + python3 benchmark_fa2_sinks.py |
| 6 | +
|
| 7 | +Parameters: |
| 8 | + so_path - path to the shared library (.so) |
| 9 | + path_new - path to save results |
| 10 | +""" |
| 11 | +import math |
| 12 | +import torch |
| 13 | +from einops import rearrange |
| 14 | +import torch.utils.benchmark as benchmark |
| 15 | +import csv |
| 16 | +import vllm |
| 17 | +import os |
| 18 | + |
| 19 | +pkg = os.path.dirname(vllm.__file__) |
| 20 | +so_path = os.path.join(pkg, "vllm_flash_attn", "_vllm_fa2_C.abi3.so") |
| 21 | +path_new = os.path.join(".", "benchmark_fa2_sinks.csv") |
| 22 | + |
| 23 | +csv_rows = [] |
| 24 | + |
| 25 | +def benchmark_forward( |
| 26 | + fn, inputs, repeats=10, desc="", verbose=False, amp=False, amp_dtype=torch.float16, **kwinputs |
| 27 | +): |
| 28 | + """Use Pytorch Benchmark on the forward pass of an arbitrary function.""" |
| 29 | + if verbose: |
| 30 | + print(desc, "- Forward pass") |
| 31 | + |
| 32 | + def amp_wrapper(inputs, **kwinputs): |
| 33 | + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): |
| 34 | + fn(*inputs) |
| 35 | + |
| 36 | + t = benchmark.Timer( |
| 37 | + stmt="fn_amp(inputs, **kwinputs)", |
| 38 | + globals={"fn_amp": amp_wrapper, "inputs": inputs, "kwinputs": kwinputs}, |
| 39 | + num_threads=torch.get_num_threads(), |
| 40 | + ) |
| 41 | + m = t.timeit(repeats) |
| 42 | + if verbose: |
| 43 | + print(m) |
| 44 | + return t, m |
| 45 | + |
| 46 | +def benchmark_fwd_bwd( |
| 47 | + fn, |
| 48 | + inputs, |
| 49 | + grad=None, |
| 50 | + repeats=10, |
| 51 | + desc="", |
| 52 | + verbose=True, |
| 53 | + amp=False, |
| 54 | + amp_dtype=torch.float16, |
| 55 | + **kwinputs, |
| 56 | +): |
| 57 | + """Use Pytorch Benchmark on the forward+backward pass of an arbitrary function.""" |
| 58 | + return benchmark_forward( |
| 59 | + fn, |
| 60 | + inputs, |
| 61 | + repeats=repeats, |
| 62 | + desc=desc, |
| 63 | + verbose=verbose, |
| 64 | + amp=amp, |
| 65 | + amp_dtype=amp_dtype, |
| 66 | + **kwinputs, |
| 67 | + ) |
| 68 | + |
| 69 | +attention_triton = None |
| 70 | +xops = None |
| 71 | + |
| 72 | +def flops(batch, seqlen, headdim, nheads, causal, mode="fwd"): |
| 73 | + assert mode in ["fwd", "bwd", "fwd_bwd"] |
| 74 | + f = 4 * batch * seqlen**2 * nheads * headdim // (2 if causal else 1) |
| 75 | + return f if mode == "fwd" else (2.5 * f if mode == "bwd" else 3.5 * f) |
| 76 | + |
| 77 | +def efficiency(flop, time): |
| 78 | + return (flop / time / 10**12) if not math.isnan(time) else 0.0 |
| 79 | + |
| 80 | + |
| 81 | +def attention_pytorch(qkv, dropout_p=0.0, causal=True): |
| 82 | + """ |
| 83 | + Arguments: |
| 84 | + qkv: (batch_size, seqlen, 3, nheads, head_dim) |
| 85 | + dropout_p: float |
| 86 | + Output: |
| 87 | + output: (batch_size, seqlen, nheads, head_dim) |
| 88 | + """ |
| 89 | + batch_size, seqlen, _, nheads, d = qkv.shape |
| 90 | + q, k, v = qkv.unbind(dim=2) |
| 91 | + q = rearrange(q, 'b t h d -> (b h) t d') |
| 92 | + k = rearrange(k, 'b s h d -> (b h) d s') |
| 93 | + softmax_scale = 1.0 / math.sqrt(d) |
| 94 | + scores = torch.empty(batch_size * nheads, seqlen, seqlen, dtype=qkv.dtype, device=qkv.device) |
| 95 | + scores = rearrange(torch.baddbmm(scores, q, k, beta=0, alpha=softmax_scale), |
| 96 | + '(b h) t s -> b h t s', h=nheads) |
| 97 | + if causal: |
| 98 | + causal_mask = torch.triu(torch.full((seqlen, seqlen), -10000.0, device=scores.device), 1) |
| 99 | + scores = scores + causal_mask.to(dtype=scores.dtype) |
| 100 | + attention = torch.softmax(scores, dim=-1) |
| 101 | + attention_drop = F.dropout(attention, dropout_p) |
| 102 | + output = torch.einsum('bhts,bshd->bthd', attention_drop , v) |
| 103 | + return output.to(dtype=qkv.dtype) |
| 104 | + |
| 105 | + |
| 106 | +def time_fwd_bwd(func, *args, **kwargs): |
| 107 | + time_f = benchmark_fwd_bwd(func, *args, **kwargs) |
| 108 | + return time_f[1].mean |
| 109 | + |
| 110 | + |
| 111 | +repeats = 30 |
| 112 | +device = 'cuda' |
| 113 | +dtype = torch.float16 |
| 114 | + |
| 115 | +bs_seqlen_vals = [(32, 512), (16, 1024), (8, 2048), (4, 4096), (2, 8192), (1, 16384)] |
| 116 | +causal_vals = [False, True] |
| 117 | +headdim_vals = [64, 128] |
| 118 | +dim = 2048 |
| 119 | +dropout_p = 0.0 |
| 120 | + |
| 121 | +time_f = {} |
| 122 | +time_b = {} |
| 123 | +time_f_b = {} |
| 124 | +speed_f = {} |
| 125 | +speed_b = {} |
| 126 | +speed_f_b = {} |
| 127 | +def test_time(path, func_name, old_or_new): |
| 128 | + for causal in causal_vals: |
| 129 | + for headdim in headdim_vals: |
| 130 | + for batch_size, seqlen in bs_seqlen_vals: |
| 131 | + config = (causal, headdim, batch_size, seqlen) |
| 132 | + nheads = dim // headdim |
| 133 | + |
| 134 | + qkv = torch.randn(batch_size, seqlen, 3, nheads, headdim, device=device, dtype=dtype, |
| 135 | + requires_grad=True) |
| 136 | + q = qkv[:, :, 0] # (B, S, H, D) |
| 137 | + k = qkv[:, :, 1] # (B, S, H, D) |
| 138 | + v = qkv[:, :, 2] # (B, S, H, D) |
| 139 | + |
| 140 | + q = q.reshape(-1, nheads, headdim) |
| 141 | + k = k.reshape(-1, nheads, headdim) |
| 142 | + v = v.reshape(-1, nheads, headdim) |
| 143 | + s_aux = torch.randn(nheads,device=device, dtype=dtype,requires_grad=True) |
| 144 | + out_buf = torch.empty_like(q) |
| 145 | + fa2_fwd_closure = [q, k, v, |
| 146 | + out_buf, |
| 147 | + torch.tensor([(seqlen)*i for i in range(batch_size+1)], device=device, dtype = torch.int32), |
| 148 | + torch.tensor([(seqlen)*i for i in range(batch_size+1)], device=device, dtype = torch.int32), |
| 149 | + None, |
| 150 | + None, |
| 151 | + None, |
| 152 | + None, |
| 153 | + seqlen, |
| 154 | + seqlen, |
| 155 | + dropout_p, |
| 156 | + torch.tensor(1.0 / (headdim ** 0.5), device=device), |
| 157 | + False, |
| 158 | + causal, |
| 159 | + -1, |
| 160 | + -1, |
| 161 | + 0.0, |
| 162 | + dropout_p > 0, |
| 163 | + None, |
| 164 | + s_aux |
| 165 | + ] |
| 166 | + f = time_fwd_bwd(func_name, fa2_fwd_closure, repeats=repeats, verbose=False) |
| 167 | + time_f[config, "Flash2"] = f |
| 168 | + print(f"### causal={causal}, headdim={headdim}, batch_size={batch_size}, seqlen={seqlen} ###") |
| 169 | + speed_f[config, "Flash2"] = efficiency( |
| 170 | + flops(batch_size, seqlen, headdim, nheads, causal, mode="fwd"), |
| 171 | + time_f[config, "Flash2"]) |
| 172 | + print( |
| 173 | + f"{"Flash2"} fwd: {speed_f[config, "Flash2"]:.2f} TFLOPs/s, " |
| 174 | + ) |
| 175 | + csv_rows.append([causal, headdim, batch_size, seqlen, f"{speed_f[config, "Flash2"]:.2f}"]) |
| 176 | + with open(path, "a", newline="") as fp: |
| 177 | + writer = csv.writer(fp) |
| 178 | + writer.writerow(["causal", "headdim", "batch_size", "seqlen", "TFLOPs/s"]) |
| 179 | + writer.writerows(csv_rows) |
| 180 | + |
| 181 | + print(f"已写入{path}") |
| 182 | + |
| 183 | +torch.ops.load_library(so_path) |
| 184 | +func_name = torch.ops._vllm_fa2_C.varlen_fwd |
| 185 | +test_time(path_new, func_name, "new") |
0 commit comments