benchmark_causal.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. from functools import partial
  2. import math
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. from einops import rearrange, repeat
  7. # from flash_attn.utils.benchmark import benchmark_forward, benchmark_backward, benchmark_combined, benchmark_all, benchmark_fwd_bwd, pytorch_profiler
  8. from flash_attn.utils.benchmark import benchmark_forward, benchmark_backward, benchmark_combined, benchmark_all, benchmark_fwd_bwd, pytorch_profiler
  9. from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func
  10. # # from flash_attn.triton.fused_attention import attention as attention
  11. # from flash_attn.flash_attn_triton import flash_attn_qkvpacked_func
  12. # from flash_attn.flash_attn_triton_og import attention as attention_og
  13. # from triton.ops.flash_attention import attention as attention_triton
  14. from flash_attn import flash_attn_qkvpacked_func, flash_attn_kvpacked_func
  15. try:
  16. from flash_attn.fused_softmax import scaled_upper_triang_masked_softmax
  17. except ImportError:
  18. scaled_upper_triang_masked_softmax = None
  19. def attention_pytorch(qkv, dropout_p=0.0, causal=True):
  20. """
  21. Arguments:
  22. qkv: (batch_size, seqlen, 3, nheads, head_dim)
  23. dropout_p: float
  24. Output:
  25. output: (batch_size, seqlen, nheads, head_dim)
  26. """
  27. batch_size, seqlen, _, nheads, d = qkv.shape
  28. q, k, v = qkv.unbind(dim=2)
  29. q = rearrange(q, 'b t h d -> (b h) t d')
  30. k = rearrange(k, 'b s h d -> (b h) d s')
  31. softmax_scale = 1.0 / math.sqrt(d)
  32. # Preallocate attn_weights for `baddbmm`
  33. scores = torch.empty(batch_size * nheads, seqlen, seqlen, dtype=qkv.dtype, device=qkv.device)
  34. scores = rearrange(torch.baddbmm(scores, q, k, beta=0, alpha=softmax_scale),
  35. '(b h) t s -> b h t s', h=nheads)
  36. if causal:
  37. # "triu_tril_cuda_template" not implemented for 'BFloat16'
  38. # So we have to construct the mask in float
  39. causal_mask = torch.triu(torch.full((seqlen, seqlen), -10000.0, device=scores.device), 1)
  40. # TD [2022-09-30]: Adding is faster than masked_fill_ (idk why, just better kernel I guess)
  41. scores = scores + causal_mask.to(dtype=scores.dtype)
  42. attention = torch.softmax(scores, dim=-1)
  43. attention_drop = F.dropout(attention, dropout_p)
  44. output = torch.einsum('bhts,bshd->bthd', attention_drop , v)
  45. return output.to(dtype=qkv.dtype)
  46. def attention_megatron(qkv):
  47. """
  48. Arguments:
  49. qkv: (batch_size, seqlen, 3, nheads, head_dim)
  50. Output:
  51. output: (batch_size, seqlen, nheads, head_dim)
  52. """
  53. batch_size, seqlen, _, nheads, d = qkv.shape
  54. q, k, v = qkv.unbind(dim=2)
  55. q = rearrange(q, 'b t h d -> (b h) t d')
  56. k = rearrange(k, 'b s h d -> (b h) d s')
  57. softmax_scale = 1.0 / math.sqrt(d)
  58. # Preallocate attn_weights for `baddbmm`
  59. scores = torch.empty(batch_size * nheads, seqlen, seqlen, dtype=qkv.dtype, device=qkv.device)
  60. scores = rearrange(torch.baddbmm(scores, q, k, beta=0, alpha=softmax_scale),
  61. '(b h) t s -> b h t s', h=nheads)
  62. attention = scaled_upper_triang_masked_softmax(scores, None, scale=1.0)
  63. output = torch.einsum('bhts,bshd->bthd', attention, v)
  64. return output.to(dtype=qkv.dtype)
  65. torch.manual_seed(0)
  66. repeats = 30
  67. batch_size = 8
  68. seqlen = 2048
  69. nheads = 12
  70. headdim = 128
  71. # nheads = 24
  72. # headdim = 64
  73. # batch_size = 64
  74. # seqlen = 512
  75. # nheads = 8
  76. # headdim = 128
  77. dropout_p = 0.0
  78. causal = True
  79. dtype = torch.float16
  80. device = 'cuda'
  81. qkv = torch.randn(batch_size, seqlen, 3, nheads, headdim, device=device, dtype=dtype,
  82. requires_grad=True)
  83. cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
  84. device=qkv.device)
  85. qkv_unpad = rearrange(qkv, 'b s ... -> (b s) ...').detach().requires_grad_(True)
  86. # benchmark_all(flash_attn_varlen_qkvpacked_func, qkv_unpad,
  87. # cu_seqlens, seqlen, dropout_p, causal=causal, repeats=repeats, desc='FlashAttention')
  88. # pytorch_profiler(flash_attn_varlen_qkvpacked_func, qkv_unpad,
  89. # cu_seqlens, seqlen, dropout_p, causal=causal, backward=True)
  90. benchmark_forward(flash_attn_qkvpacked_func, qkv, dropout_p, causal=causal, repeats=repeats, desc='Fav2')
  91. pytorch_profiler(flash_attn_qkvpacked_func, qkv, dropout_p, causal=causal, backward=False)
  92. # for dropout_p in [0.1, 0.0]:
  93. # for causal in [False, True]:
  94. # print(f"### {dropout_p = }, {causal = } ###")
  95. # pytorch_profiler(fav2_qkvpacked_func, qkv, dropout_p, causal=causal, backward=True)
  96. # nheads_k = 2
  97. # q = torch.randn(batch_size, seqlen, nheads, headdim, device=device, dtype=dtype, requires_grad=True)
  98. # kv = torch.randn(batch_size, seqlen, 2, nheads_k, headdim, device=device, dtype=dtype,
  99. # requires_grad=True)
  100. # if fav2_kvpacked_func is not None:
  101. # benchmark_all(fav2_kvpacked_func, q, kv, dropout_p, causal=causal, repeats=repeats, desc='Fav2')
  102. # pytorch_profiler(fav2_kvpacked_func, q, kv, dropout_p, causal=causal, backward=True)
  103. # dropout_p = 0.0
  104. # causal = False
  105. # benchmark_all(attention_pytorch, qkv, dropout_p, causal=causal,
  106. # repeats=repeats, desc='PyTorch Attention')
  107. # benchmark_all(flash_attn_qkvpacked_func, qkv, None, causal, repeats=repeats, desc='FlashAttention Triton')
  108. # pytorch_profiler(flash_attn_qkvpacked_func, qkv, None, causal, backward=True)
  109. # q, k, v = [torch.randn(batch_size, nheads, seqlen, headdim, device=device, dtype=dtype,
  110. # requires_grad=True) for _ in range(3)]
  111. # benchmark_all(attention_og, q, k, v, 1.0, repeats=repeats, desc='FlashAttention Triton OG')
  112. # # pytorch_profiler(attention, q, k, v, 1.0, backward=True)
  113. # if scaled_upper_triang_masked_softmax is not None:
  114. # benchmark_all(attention_megatron, qkv, repeats=repeats, desc='Megatron Attention')
  115. # from src.ops.fftconv import fftconv_func
  116. # dim = nheads * headdim
  117. # u = torch.randn(batch_size, dim, seqlen, device=device, dtype=dtype, requires_grad=True)
  118. # k = torch.randn(dim, seqlen, device=device, requires_grad=True)
  119. # D = torch.randn(dim, device=device, requires_grad=True)
  120. # benchmark_all(fftconv_func, u, k, D, repeats=repeats, desc='FFTConv')
  121. # pytorch_profiler(fftconv_func, u, k, D, backward=True)
  122. # pytorch_profiler(torch.fft.rfft, u.float())
  123. flops = 4 * batch_size * seqlen ** 2 * nheads * headdim
  124. ideal_a100_time = flops / 312 / 1e9
  125. print(f"Ideal A100 fwd time: {ideal_a100_time:.3f}ms, bwd time: {ideal_a100_time * 2.5:.3f}ms")
  126. exit(0)
  127. def time_fwd_bwd(func, *args, **kwargs):
  128. time_f, time_b = benchmark_fwd_bwd(func, *args, **kwargs)
  129. return time_f[1].mean, time_b[1].mean
  130. bs_seqlen_vals = [(32, 512), (16, 1024), (8, 2048), (4, 4096), (2, 8192), (1, 16384)]
  131. causal_vals = [False, True]
  132. headdim_vals = [64, 128]
  133. dim = 2048
  134. dropout_p = 0.0
  135. time_f = {}
  136. time_b = {}
  137. for causal in causal_vals:
  138. for headdim in headdim_vals:
  139. for batch_size, seqlen in bs_seqlen_vals:
  140. nheads = dim // headdim
  141. qkv = torch.randn(batch_size, seqlen, 3, nheads, headdim, device=device, dtype=dtype,
  142. requires_grad=True)
  143. cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
  144. device=qkv.device)
  145. qkv_unpad = rearrange(qkv, 'b s ... -> (b s) ...').detach().requires_grad_(True)
  146. f, b = time_fwd_bwd(
  147. flash_attn_varlen_qkvpacked_func, qkv_unpad, cu_seqlens, seqlen, dropout_p,
  148. causal=causal, repeats=repeats, verbose=False
  149. )
  150. time_f[(causal, headdim, batch_size, seqlen), "Flash"] = f
  151. time_b[(causal, headdim, batch_size, seqlen), "Flash"] = b
  152. qkv = qkv.detach().requires_grad_(True)
  153. f, b = time_fwd_bwd(
  154. fav2_qkvpacked_func, qkv, dropout_p, causal=causal, repeats=repeats, verbose=False
  155. )
  156. time_f[(causal, headdim, batch_size, seqlen), "Flash2"] = f
  157. time_b[(causal, headdim, batch_size, seqlen), "Flash2"] = b
  158. # q, k, v = [torch.randn(batch_size, nheads, seqlen, headdim, device=device, dtype=dtype,
  159. # requires_grad=True) for _ in range(3)]
  160. # # Try both values of sequence_parallel and pick the faster one
  161. # f, b = time_fwd_bwd(
  162. # attention_triton, q, k, v, causal, headdim**(-0.5),
  163. # False, repeats=repeats, verbose=False
  164. # )
  165. # _, b0 = time_fwd_bwd(
  166. # attention_triton, q, k, v, causal, headdim**(-0.5),
  167. # True, repeats=repeats, verbose=False
  168. # )
  169. # time_f[(causal, headdim, batch_size, seqlen), "Triton"] = f
  170. # time_b[(causal, headdim, batch_size, seqlen), "Triton"] = min(b, b0)
  171. if seqlen <= 8 * 1024:
  172. qkv = qkv.detach().requires_grad_(True)
  173. f, b = time_fwd_bwd(
  174. attention_pytorch, qkv, dropout_p, causal=causal, repeats=repeats, verbose=False
  175. )
  176. else:
  177. f, b = float('nan'), float('nan')
  178. time_f[(causal, headdim, batch_size, seqlen), "Pytorch"] = f
  179. time_b[(causal, headdim, batch_size, seqlen), "Pytorch"] = b
  180. # q, k, v = [torch.randn(batch_size, seqlen, nheads, headdim, device=device, dtype=dtype,
  181. # requires_grad=True) for _ in range(3)]
  182. # import xformers.ops as xops
  183. # f, b = time_fwd_bwd(
  184. # xops.memory_efficient_attention, q, k, v,
  185. # attn_bias=xops.LowerTriangularMask() if causal else None,
  186. # op=(xops.fmha.cutlass.FwOp, xops.fmha.cutlass.BwOp)
  187. # )
  188. # time_f[(causal, headdim, batch_size, seqlen), "xformers"] = f
  189. # time_b[(causal, headdim, batch_size, seqlen), "xformers"] = b
  190. import pickle
  191. with open('flash2_attn_time_h100.plk', 'wb') as fp:
  192. pickle.dump((time_f, time_b), fp, protocol=pickle.HIGHEST_PROTOCOL)