test_flash_attn.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. import os
  2. import math
  3. import itertools
  4. import pytest
  5. import torch
  6. import torch.nn.functional as F
  7. from einops import rearrange, repeat
  8. from flash_attn.layers.rotary import apply_rotary_emb
  9. from test_util import (
  10. attention_ref,
  11. generate_qkv,
  12. generate_random_padding_mask,
  13. )
  14. from flash_attn_interface import flash_attn_func, flash_attn_varlen_func, flash_attn_combine, flash_attn_with_kvcache
  15. DISABLE_BACKWARD = os.getenv("FLASH_ATTENTION_DISABLE_BACKWARD", "FALSE") == "TRUE"
  16. DISABLE_SPLIT = os.getenv("FLASH_ATTENTION_DISABLE_SPLIT", "FALSE") == "TRUE"
  17. DISABLE_PAGEDKV = os.getenv("FLASH_ATTENTION_DISABLE_PAGEDKV", "FALSE") == "TRUE"
  18. DISABLE_APPENDKV = os.getenv("FLASH_ATTENTION_DISABLE_APPENDKV", "FALSE") == "TRUE"
  19. DISABLE_LOCAL = os.getenv("FLASH_ATTENTION_DISABLE_LOCAL", "FALSE") == "TRUE"
  20. DISABLE_SOFTCAP = os.getenv("FLASH_ATTENTION_DISABLE_SOFTCAP", "FALSE") == "TRUE"
  21. DISABLE_PACKGQA = os.getenv("FLASH_ATTENTION_DISABLE_PACKGQA", "FALSE") == "TRUE"
  22. DISABLE_FP16 = os.getenv("FLASH_ATTENTION_DISABLE_FP16", "FALSE") == "TRUE"
  23. DISABLE_FP8 = os.getenv("FLASH_ATTENTION_DISABLE_FP8", "FALSE") == "TRUE"
  24. DISABLE_HDIM64 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM64", "FALSE") == "TRUE"
  25. DISABLE_HDIM96 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM96", "FALSE") == "TRUE"
  26. DISABLE_HDIM128 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM128", "FALSE") == "TRUE"
  27. DISABLE_HDIM192 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM192", "FALSE") == "TRUE"
  28. DISABLE_HDIM256 = os.getenv("FLASH_ATTENTION_DISABLE_HDIM256", "FALSE") == "TRUE"
  29. COMPILED_HDIMS = (
  30. []
  31. + ([64] if not DISABLE_HDIM64 else [])
  32. + ([96] if not DISABLE_HDIM96 else [])
  33. + ([128] if not DISABLE_HDIM128 else [])
  34. + ([192] if not DISABLE_HDIM192 else [])
  35. + ([256] if not DISABLE_HDIM256 else [])
  36. )
  37. # @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float8_e4m3fn])
  38. @pytest.mark.parametrize("dtype", [torch.bfloat16] + ([torch.float16] if not DISABLE_FP16 else []) + ([torch.float8_e4m3fn] if not DISABLE_FP8 else []))
  39. # @pytest.mark.parametrize("dtype", [torch.bfloat16])
  40. # @pytest.mark.parametrize("dtype", [torch.float8_e4m3fn])
  41. @pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"])
  42. # @pytest.mark.parametrize("mha_type", ["mha"])
  43. # @pytest.mark.parametrize("deterministic", [False, True])
  44. @pytest.mark.parametrize("deterministic", [False])
  45. @pytest.mark.parametrize("softcap", [0.0] + ([30.0] if not DISABLE_SOFTCAP else []))
  46. # @pytest.mark.parametrize("softcap", [0.0])
  47. @pytest.mark.parametrize("local", [False] + ([True] if not DISABLE_LOCAL else []))
  48. # @pytest.mark.parametrize("local", [False])
  49. @pytest.mark.parametrize("causal", [False, True])
  50. # @pytest.mark.parametrize("causal", [False])
  51. # @pytest.mark.parametrize("V_colmajor", [False, True])
  52. @pytest.mark.parametrize("V_colmajor", [False])
  53. # @pytest.mark.parametrize("d", [32, 64, 96, 128, 160, 192, 224, 256])
  54. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192, 256])
  55. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192])
  56. # @pytest.mark.parametrize('d', [56, 80])
  57. # @pytest.mark.parametrize("d", [64, 128, 256])
  58. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128])
  59. # @pytest.mark.parametrize("d", [64, 96, 128, 192])
  60. @pytest.mark.parametrize("d", COMPILED_HDIMS)
  61. # @pytest.mark.parametrize("d", [128])
  62. @pytest.mark.parametrize(
  63. "seqlen_q,seqlen_k",
  64. [
  65. (1, 1),
  66. (64, 128),
  67. (128, 192),
  68. (256, 256),
  69. (239, 1),
  70. (799, 3),
  71. (113, 203),
  72. (113, 128),
  73. (128, 217),
  74. (113, 211),
  75. (108, 256),
  76. (256, 512),
  77. (384, 256),
  78. (640, 128),
  79. (512, 256),
  80. (1024, 1024),
  81. (1023, 1024),
  82. (1024, 1023),
  83. (4096, 4096),
  84. (4224, 4224),
  85. ],
  86. )
  87. # @pytest.mark.parametrize('seqlen_q,seqlen_k', [(128, 128)])
  88. def test_flash_attn_output(
  89. seqlen_q, seqlen_k, d, causal, local, softcap, V_colmajor, deterministic, mha_type, dtype
  90. ):
  91. # sink_token_length = 0 if not local else 4
  92. sink_token_length = 0 if not local else 0
  93. if V_colmajor and (seqlen_k % 16 != 0 or dtype != torch.float8_e4m3fn):
  94. pytest.skip("V_colmajor requires seqlen_k to be a multiple of 16 and dtype to be float8_e4m3fn")
  95. device = "cuda"
  96. # set seed
  97. torch.random.manual_seed(0)
  98. # batch_size = 40
  99. # nheads = 16
  100. batch_size = 9 if seqlen_k <= 2048 else 2
  101. # batch_size = 1
  102. nheads = 6
  103. # nheads = 1
  104. nheads_kv = nheads if mha_type == "mha" else (2 if mha_type == "gqa" else 1)
  105. dtype_ref = torch.bfloat16 if dtype == torch.float8_e4m3fn else dtype
  106. q_ref = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype_ref)
  107. if softcap > 0.0:
  108. # Ensure the values of qk are at least within softcap range.
  109. q_ref = (q_ref * softcap / 4)
  110. q_ref = q_ref.to(dtype).to(dtype_ref).requires_grad_()
  111. k_ref = torch.randn(batch_size, seqlen_k, nheads_kv, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref).requires_grad_()
  112. v_ref = torch.randn(batch_size, seqlen_k, nheads_kv, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref).requires_grad_()
  113. # Put window_size after QKV randn so that window_size changes from test to test
  114. window_size = (-1, -1) if not local else torch.randint(0, seqlen_k, (2,))
  115. # window_size = (-1, -1) if not local else (16, 0)
  116. if dtype == torch.float8_e4m3fn:
  117. q_descale, k_descale, v_descale = [torch.rand(batch_size, nheads_kv, device=device, dtype=torch.float32) * 2 for _ in range(3)]
  118. else:
  119. q_descale, k_descale, v_descale = None, None, None
  120. q, k, v = [x.detach().to(dtype).requires_grad_() for x in (q_ref, k_ref, v_ref)]
  121. if V_colmajor:
  122. v = rearrange(rearrange(v.detach(), "b s h d -> b h d s").contiguous(), "b h d s -> b s h d").requires_grad_()
  123. out_ref, attn_ref = attention_ref(
  124. q_ref,
  125. k_ref,
  126. v_ref,
  127. None,
  128. None,
  129. causal=causal,
  130. q_descale=q_descale, k_descale=k_descale, v_descale=v_descale,
  131. window_size=window_size,
  132. sink_token_length=sink_token_length,
  133. softcap=softcap
  134. )
  135. out_pt, attn_pt = attention_ref(
  136. q_ref,
  137. k_ref,
  138. v_ref,
  139. None,
  140. None,
  141. causal=causal,
  142. q_descale=q_descale, k_descale=k_descale, v_descale=v_descale,
  143. window_size=window_size,
  144. sink_token_length=sink_token_length,
  145. softcap=softcap,
  146. upcast=False,
  147. reorder_ops=True,
  148. intermediate_dtype=dtype if dtype == torch.float8_e4m3fn else None,
  149. )
  150. # qk = torch.einsum('bshd,bthd->bhst', q_ref, k_ref).float()
  151. # m = qk.amax(-1, keepdim=True)
  152. # s_tmp = torch.exp((qk - m) / math.sqrt(d))
  153. # exp_sum = s_tmp.sum(-1)
  154. # qk = torch.einsum('bthd,bshd->bhts', q_ref.float() / math.sqrt(d), k_ref.float())
  155. # lse_ref = torch.logsumexp(qk, dim=-1)
  156. abs_tol = 5e-5 if softcap == 0.0 else 5e-4
  157. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  158. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  159. pack_gqa_vals = [False, True] if not DISABLE_PACKGQA else [False]
  160. num_splits_vals = [1, 3] if not DISABLE_SPLIT else [1]
  161. for pack_gqa, num_splits in itertools.product(pack_gqa_vals, num_splits_vals):
  162. out, lse = flash_attn_func(
  163. q,
  164. k,
  165. v,
  166. causal=causal,
  167. q_descale=q_descale, k_descale=k_descale, v_descale=v_descale,
  168. window_size=window_size,
  169. sink_token_length=sink_token_length,
  170. softcap=softcap,
  171. pack_gqa=pack_gqa,
  172. num_splits=num_splits
  173. )
  174. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  175. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  176. # if not causal:
  177. # print(f"LSE max diff: {(lse - lse_ref).abs().max().item()}")
  178. # breakpoint()
  179. # Check that FlashAttention's numerical error is at most twice the numerical error
  180. # of a Pytorch implementation.
  181. multiple = 2 if dtype != torch.float8_e4m3fn else 3
  182. assert (out - out_ref).abs().max().item() <= multiple * (out_pt - out_ref).abs().max().item() + abs_tol
  183. if not DISABLE_BACKWARD and dtype != torch.float8_e4m3fn and not V_colmajor:
  184. g = torch.randn_like(out)
  185. do_o = ((g.float() * out.float()).sum(-1)).transpose(1, 2)
  186. # import flash_attn_3_cuda
  187. # dq, dk, dv, softmax_d, dq_accum, dk_accum, dv_accum = flash_attn_3_cuda.bwd(
  188. # g,
  189. # q,
  190. # k,
  191. # v,
  192. # out,
  193. # lse,
  194. # None,
  195. # None,
  196. # None,
  197. # d ** (-0.5),
  198. # causal,
  199. # window_size[0], window_size[1],
  200. # sink_token_length,
  201. # softcap,
  202. # deterministic,
  203. # 0, # sm_margin
  204. # )
  205. dq, dk, dv = torch.autograd.grad(out, (q, k, v), g)
  206. # print(f"dO_O max diff: {(softmax_d - do_o).abs().max().item()}")
  207. # assert (softmax_d - do_o).abs().max().item() <= 1e-5
  208. # assert dq_accum.abs().max().item() == 0.0
  209. # dS = torch.einsum('bthd,bshd->bhts', g.float(), v.float())
  210. # P = torch.softmax(qk, -1)
  211. # dP = P * (dS - do_o.transpose(1, 2).unsqueeze(1))
  212. # dQ = torch.einsum('bhts,bshd->bthd', dP, k.float())
  213. # dV = torch.einsum('bhts,bthd->bshd', P, g.float())
  214. # dK = torch.einsum('bhts,bthd->bshd', dP, q.float())
  215. # dq, dk, dv = torch.autograd.grad(out, (q, k, v), g)
  216. dq_ref, dk_ref, dv_ref = torch.autograd.grad(out_ref, (q_ref, k_ref, v_ref), g)
  217. dq_pt, dk_pt, dv_pt = torch.autograd.grad(out_pt, (q_ref, k_ref, v_ref), g)
  218. print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}")
  219. print(f"dK max diff: {(dk - dk_ref).abs().max().item()}")
  220. print(f"dV max diff: {(dv - dv_ref).abs().max().item()}")
  221. print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}")
  222. print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}")
  223. print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}")
  224. print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}")
  225. print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}")
  226. print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}")
  227. print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}")
  228. print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}")
  229. print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}")
  230. # breakpoint()
  231. if not DISABLE_BACKWARD and dtype != torch.float8_e4m3fn and not V_colmajor:
  232. multiple = 2
  233. assert (dq - dq_ref).abs().max().item() <= multiple * (dq_pt - dq_ref).abs().max().item() + abs_tol
  234. assert (dk - dk_ref).abs().max().item() <= multiple * (dk_pt - dk_ref).abs().max().item() + abs_tol
  235. assert (dv - dv_ref).abs().max().item() <= multiple * (dv_pt - dv_ref).abs().max().item() + abs_tol
  236. # @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float8_e4m3fn])
  237. @pytest.mark.parametrize("dtype", [torch.bfloat16] + ([torch.float16] if not DISABLE_FP16 else []) + ([torch.float8_e4m3fn] if not DISABLE_FP8 else []))
  238. # @pytest.mark.parametrize("dtype", [torch.bfloat16])
  239. # @pytest.mark.parametrize("dtype", [torch.float8_e4m3fn])
  240. @pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"])
  241. # @pytest.mark.parametrize("mha_type", ["mha"])
  242. # @pytest.mark.parametrize("deterministic", [False, True])
  243. @pytest.mark.parametrize("deterministic", [False])
  244. @pytest.mark.parametrize("softcap", [0.0] + ([30.0] if not DISABLE_SOFTCAP else []))
  245. # @pytest.mark.parametrize("softcap", [0.0])
  246. @pytest.mark.parametrize("local", [False] + ([True] if not DISABLE_LOCAL else []))
  247. # @pytest.mark.parametrize("local", [False])
  248. @pytest.mark.parametrize("causal", [False, True])
  249. # @pytest.mark.parametrize("causal", [False])
  250. @pytest.mark.parametrize("add_unused_qkv", [False, True])
  251. # @pytest.mark.parametrize("add_unused_qkv", [True])
  252. # @pytest.mark.parametrize("d", [32, 64, 96, 128, 160, 192, 224, 256])
  253. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192, 256])
  254. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192])
  255. # @pytest.mark.parametrize('d', [56, 80])
  256. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128])
  257. # @pytest.mark.parametrize("d", [64, 96, 128])
  258. @pytest.mark.parametrize("d", COMPILED_HDIMS)
  259. # @pytest.mark.parametrize("d", [128])
  260. @pytest.mark.parametrize(
  261. "seqlen_q,seqlen_k",
  262. [
  263. (1, 1),
  264. (1, 3),
  265. (2, 1),
  266. (511, 1),
  267. (3, 513),
  268. (64, 128),
  269. (128, 128),
  270. (256, 256),
  271. (113, 203),
  272. (128, 217),
  273. (113, 211),
  274. (108, 256),
  275. (256, 512),
  276. (307, 256),
  277. (640, 128),
  278. (512, 256),
  279. (1024, 1024),
  280. (1023, 1024),
  281. (1024, 1023),
  282. (2048, 2048),
  283. ],
  284. )
  285. def test_flash_attn_varlen_output(
  286. seqlen_q, seqlen_k, d, add_unused_qkv, causal, local, softcap, deterministic, mha_type, dtype
  287. ):
  288. device = "cuda"
  289. # set seed
  290. torch.random.manual_seed(seqlen_q + seqlen_k + d + int(causal) * 2 + int(local))
  291. # batch_size = 40
  292. # nheads = 16
  293. batch_size = 9 if seqlen_q <= 2048 else 2
  294. nheads = 6
  295. # batch_size = 2
  296. # nheads = 1
  297. nheads_kv = nheads if mha_type == "mha" else (2 if mha_type == "gqa" else 1)
  298. dtype_ref = torch.bfloat16 if dtype == torch.float8_e4m3fn else dtype
  299. q_ref = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype_ref)
  300. if softcap > 0.0:
  301. # Ensure the values of qk are at least within softcap range.
  302. q_ref = (q_ref * softcap / 4).detach().requires_grad_()
  303. q_ref = q_ref.to(dtype).to(dtype_ref).requires_grad_()
  304. k_ref = torch.randn(batch_size, seqlen_k, nheads_kv, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref).requires_grad_()
  305. v_ref = torch.randn(batch_size, seqlen_k, nheads_kv, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref).requires_grad_()
  306. # Put window_size after QKV randn so that window_size changes from test to test
  307. window_size = (-1, -1) if not local else torch.randint(0, seqlen_k, (2,))
  308. if dtype == torch.float8_e4m3fn:
  309. q_descale, k_descale, v_descale = [torch.rand(batch_size, nheads_kv, device=device, dtype=torch.float32) * 2 for _ in range(3)]
  310. else:
  311. q_descale, k_descale, v_descale = None, None, None
  312. q, k, v = [x.detach().requires_grad_() for x in (q_ref, k_ref, v_ref)]
  313. query_padding_mask = generate_random_padding_mask(
  314. seqlen_q, batch_size, device, mode="random", zero_lengths=False
  315. )
  316. key_padding_mask = generate_random_padding_mask(
  317. seqlen_k, batch_size, device, mode="random", zero_lengths=True
  318. )
  319. def _gen_unused_masks(padding_mask, add_unused, max_seq_len, bs, device):
  320. if add_unused:
  321. another_mask = generate_random_padding_mask(max_seq_len, bs, device)
  322. attn_mask = torch.logical_and(padding_mask, another_mask)
  323. unused_mask = torch.logical_xor(
  324. torch.logical_or(padding_mask, another_mask), attn_mask
  325. )
  326. else:
  327. attn_mask = padding_mask
  328. unused_mask = None
  329. return attn_mask, unused_mask
  330. query_padding_mask, query_unused_mask = _gen_unused_masks(
  331. query_padding_mask, add_unused_qkv, seqlen_q, batch_size, q.device
  332. )
  333. key_padding_mask, key_unused_mask = _gen_unused_masks(
  334. key_padding_mask, add_unused_qkv, seqlen_k, batch_size, k.device
  335. )
  336. (
  337. q_unpad,
  338. k_unpad,
  339. v_unpad,
  340. cu_seqlens_q,
  341. cu_seqlens_k,
  342. seqused_q,
  343. seqused_k,
  344. max_seqlen_q,
  345. max_seqlen_k,
  346. q,
  347. k,
  348. v,
  349. output_pad_fn,
  350. dq_pad_fn,
  351. dk_pad_fn,
  352. ) = generate_qkv(q, k, v, query_padding_mask, key_padding_mask, kvpacked=False,
  353. query_unused_mask=query_unused_mask, key_unused_mask=key_unused_mask)
  354. q_unpad, k_unpad, v_unpad = [x.detach().to(dtype).requires_grad_() for x in (q_unpad, k_unpad, v_unpad)]
  355. out_ref, attn_ref = attention_ref(
  356. q_ref,
  357. k_ref,
  358. v_ref,
  359. query_padding_mask,
  360. key_padding_mask,
  361. causal=causal,
  362. q_descale=q_descale, k_descale=k_descale, v_descale=v_descale,
  363. window_size=window_size,
  364. softcap=softcap
  365. )
  366. out_pt, attn_pt = attention_ref(
  367. q_ref,
  368. k_ref,
  369. v_ref,
  370. query_padding_mask,
  371. key_padding_mask,
  372. causal=causal,
  373. q_descale=q_descale, k_descale=k_descale, v_descale=v_descale,
  374. window_size=window_size,
  375. softcap=softcap,
  376. upcast=False,
  377. reorder_ops=True,
  378. intermediate_dtype=dtype if dtype == torch.float8_e4m3fn else None,
  379. )
  380. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  381. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  382. if query_unused_mask is not None:
  383. q_zero_masking = rearrange(query_unused_mask, "b s -> b s 1 1")
  384. abs_tol = 5e-5 if softcap == 0.0 else 5e-4
  385. pack_gqa_vals = [False, True] if not DISABLE_PACKGQA else [False]
  386. num_splits_vals = [1, 3] if not DISABLE_SPLIT else [1]
  387. for pack_gqa, num_splits in itertools.product(pack_gqa_vals, num_splits_vals):
  388. out_unpad, lse = flash_attn_varlen_func(
  389. q_unpad,
  390. k_unpad,
  391. v_unpad,
  392. cu_seqlens_q,
  393. cu_seqlens_k,
  394. seqused_q, seqused_k,
  395. max_seqlen_q,
  396. max_seqlen_k,
  397. causal=causal,
  398. q_descale=q_descale,
  399. k_descale=k_descale, v_descale=v_descale,
  400. window_size=window_size,
  401. softcap=softcap,
  402. )
  403. out = output_pad_fn(out_unpad)
  404. if query_unused_mask is not None:
  405. out.masked_fill_(q_zero_masking, 0.0)
  406. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  407. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  408. # if not causal:
  409. # print(f"LSE max diff: {(lse - lse_ref).abs().max().item()}")
  410. # breakpoint()
  411. # Check that FlashAttention's numerical error is at most twice the numerical error
  412. # of a Pytorch implementation.
  413. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item() + abs_tol
  414. if not DISABLE_BACKWARD and dtype != torch.float8_e4m3fn:
  415. g_unpad = torch.randn_like(out_unpad)
  416. do_o = ((g_unpad.float() * out_unpad.float()).sum(-1)).transpose(-1, -2)
  417. # import flash_attn_3_cuda
  418. # dq_unpad, dk_unpad, dv_unpad, softmax_d, dq_accum, lse_log2 = flash_attn_3_cuda.bwd_varlen(
  419. # g_unpad,
  420. # q_unpad,
  421. # k_unpad,
  422. # v_unpad,
  423. # out_unpad,
  424. # lse,
  425. # None,
  426. # None,
  427. # None,
  428. # cu_seqlens_q,
  429. # cu_seqlens_k,
  430. # None, None,
  431. # max_seqlen_q,
  432. # max_seqlen_k,
  433. # d ** (-0.5),
  434. # causal,
  435. # window_size[0], window_size[1],
  436. # softcap,
  437. # deterministic,
  438. # 0, # sm_margin
  439. # )
  440. dq_unpad, dk_unpad, dv_unpad = torch.autograd.grad(out_unpad, (q_unpad, k_unpad, v_unpad), g_unpad)
  441. dq = dq_pad_fn(dq_unpad)
  442. dk = dk_pad_fn(dk_unpad)
  443. dv = dk_pad_fn(dv_unpad)
  444. if key_unused_mask is not None:
  445. k_zero_masking = rearrange(key_unused_mask, "b s -> b s 1 1")
  446. dk.masked_fill_(k_zero_masking, 0.0)
  447. dv.masked_fill_(k_zero_masking, 0.0)
  448. if query_unused_mask is not None:
  449. dq.masked_fill_(q_zero_masking, 0.0)
  450. # print(f"dO_O max diff: {(softmax_d - do_o).abs().max().item()}")
  451. # assert (softmax_d - do_o).abs().max().item() <= 1e-5
  452. # assert dq_accum.abs().max().item() == 0.0
  453. g = output_pad_fn(g_unpad)
  454. # qk = torch.einsum('bthd,bshd->bhts', q / (d ** 0.5), k).float()
  455. # qk = torch.masked_fill(qk, rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf"))
  456. # dS = torch.einsum('bthd,bshd->bhts', g.float(), v.float())
  457. # P = torch.softmax(qk, -1)
  458. # dP = P * (dS - (g.float() * out.float()).sum(-1).transpose(1, 2).unsqueeze(-1))
  459. # dQ = torch.einsum('bhts,bshd->bthd', dP, k.float())
  460. # dV = torch.einsum('bhts,bthd->bshd', P, g.float())
  461. # dK = torch.einsum('bhts,bthd->bshd', dP, q.float())
  462. # dq, dk, dv = torch.autograd.grad(out, (q, k, v), g)
  463. dq_ref, dk_ref, dv_ref = torch.autograd.grad(out_ref, (q_ref, k_ref, v_ref), g)
  464. dq_pt, dk_pt, dv_pt = torch.autograd.grad(out_pt, (q_ref, k_ref, v_ref), g)
  465. print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}")
  466. print(f"dK max diff: {(dk - dk_ref).abs().max().item()}")
  467. print(f"dV max diff: {(dv - dv_ref).abs().max().item()}")
  468. print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}")
  469. print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}")
  470. print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}")
  471. print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}")
  472. print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}")
  473. print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}")
  474. print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}")
  475. print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}")
  476. print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}")
  477. # breakpoint()
  478. if not DISABLE_BACKWARD and dtype != torch.float8_e4m3fn:
  479. multiple = 2
  480. assert (dq - dq_ref).abs().max().item() <= multiple * (dq_pt - dq_ref).abs().max().item() + abs_tol
  481. assert (dk - dk_ref).abs().max().item() <= multiple * (dk_pt - dk_ref).abs().max().item() + abs_tol
  482. assert (dv - dv_ref).abs().max().item() <= multiple * (dv_pt - dv_ref).abs().max().item() + abs_tol
  483. # @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16, torch.float8_e4m3fn])
  484. @pytest.mark.parametrize("dtype", [torch.bfloat16] + ([torch.float8_e4m3fn] if not DISABLE_FP8 else []))
  485. # @pytest.mark.parametrize("dtype", [torch.bfloat16])
  486. # @pytest.mark.parametrize("dtype", [torch.float8_e4m3fn])
  487. @pytest.mark.parametrize("num_splits", [1] + ([0] if not DISABLE_SPLIT else []))
  488. # @pytest.mark.parametrize("num_splits", [1])
  489. @pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"])
  490. # @pytest.mark.parametrize("mha_type", ["mha"])
  491. @pytest.mark.parametrize("new_kv", [False] + ([True] if not DISABLE_APPENDKV else []))
  492. # @pytest.mark.parametrize("new_kv", [True])
  493. # @pytest.mark.parametrize("local", [False, True])
  494. @pytest.mark.parametrize("causal,local", [(False, False), (True, False)] + ([(False, True)] if not DISABLE_LOCAL else []))
  495. # @pytest.mark.parametrize("causal,local", [(False, False), (True, False)])
  496. # @pytest.mark.parametrize("causal,local", [(False, False)])
  497. @pytest.mark.parametrize("seqlen_new_eq_seqlen_q", [True, False] if not DISABLE_APPENDKV else [True])
  498. # @pytest.mark.parametrize("seqlen_new_eq_seqlen_q", [True])
  499. @pytest.mark.parametrize("rotary_interleaved", [False, True] if not DISABLE_APPENDKV else [False])
  500. # @pytest.mark.parametrize("rotary_interleaved", [True])
  501. @pytest.mark.parametrize("rotary_fraction", [0.0, 0.5, 1.0] if not DISABLE_APPENDKV else [0.0])
  502. # @pytest.mark.parametrize("rotary_fraction", [0.0])
  503. @pytest.mark.parametrize("page_size", [None] + ([1, 4, 128] if not DISABLE_PAGEDKV else []))
  504. # @pytest.mark.parametrize("page_size", [None])
  505. @pytest.mark.parametrize("has_leftpad", [False, True])
  506. # @pytest.mark.parametrize("has_leftpad", [False])
  507. @pytest.mark.parametrize("has_batch_idx", [False, True])
  508. # @pytest.mark.parametrize("has_batch_idx", [False])
  509. @pytest.mark.parametrize("varlen_q", [False, True])
  510. # @pytest.mark.parametrize("varlen_q", [True])
  511. # @pytest.mark.parametrize("d", [32, 59, 64, 80, 128, 256])
  512. # @pytest.mark.parametrize("d", [32, 64, 96, 128, 160, 192, 224, 256])
  513. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192])
  514. # @pytest.mark.parametrize('d', [56, 80])
  515. @pytest.mark.parametrize("d", [128])
  516. @pytest.mark.parametrize(
  517. "seqlen_q,seqlen_k",
  518. [
  519. (1, 128),
  520. (1, 339),
  521. (3, 1024),
  522. (64, 800),
  523. (64, 256),
  524. (3, 799),
  525. (64, 2048),
  526. (16, 20000),
  527. (1, 128 * 1024),
  528. (16, 128 * 1024),
  529. (128, 128),
  530. (256, 512), # To test appending KV with more than 1 block
  531. (2048, 3577), # Enough tile to test persistent scheduler
  532. ],
  533. )
  534. # @pytest.mark.parametrize('seqlen_q,seqlen_k', [(256, 128)])
  535. def test_flash_attn_kvcache(
  536. seqlen_q,
  537. seqlen_k,
  538. d,
  539. varlen_q,
  540. has_batch_idx,
  541. has_leftpad,
  542. page_size,
  543. rotary_fraction,
  544. rotary_interleaved,
  545. seqlen_new_eq_seqlen_q,
  546. causal,
  547. local,
  548. new_kv,
  549. mha_type,
  550. num_splits,
  551. dtype,
  552. ):
  553. if page_size is not None and seqlen_k % page_size != 0:
  554. pytest.skip()
  555. if seqlen_q > seqlen_k and new_kv:
  556. pytest.skip()
  557. if not new_kv and rotary_fraction > 0.0:
  558. pytest.skip()
  559. device = "cuda"
  560. # set seed
  561. torch.random.manual_seed(0)
  562. batch_size = 5
  563. # batch_size = 1
  564. batch_size_cache = batch_size if not has_batch_idx else batch_size * 2
  565. nheads = 6
  566. # nheads = 1
  567. # rotary_dim must be a multiple of 16, and must be <= d
  568. rotary_dim = math.floor(int(rotary_fraction * d) / 16) * 16
  569. nheads_k = nheads if mha_type == "mha" else (1 if mha_type == "mqa" else 3)
  570. assert nheads % nheads_k == 0
  571. dtype_ref = torch.bfloat16 if dtype == torch.float8_e4m3fn else dtype
  572. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref)
  573. if varlen_q:
  574. query_padding_mask = generate_random_padding_mask(seqlen_q, batch_size, device, mode="random")
  575. q_unpad, indices_q, cu_seqlens_q, max_seqlen_q, *rest = unpad_input(q, query_padding_mask)
  576. output_pad_fn = lambda output_unpad: pad_input(
  577. output_unpad, indices_q, batch_size, seqlen_q
  578. )
  579. else:
  580. query_padding_mask = None
  581. q_unpad = q
  582. cu_seqlens_q, max_seqlen_q = None, None
  583. # Put window_size after QKV randn so that window_size changes from test to test
  584. window_size = (-1, -1) if not local else torch.randint(0, seqlen_k, (2,))
  585. seqlen_new = seqlen_q if seqlen_new_eq_seqlen_q else torch.randint(1, seqlen_q + 1, (1,)).item()
  586. cu_seqlens_k_new = None
  587. key_new_padding_mask = None
  588. if new_kv:
  589. k = torch.randn(batch_size, seqlen_new, nheads_k, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref)
  590. v = torch.randn(batch_size, seqlen_new, nheads_k, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref)
  591. if varlen_q: # k & v are also varlen
  592. key_new_padding_mask = generate_random_padding_mask(seqlen_new, batch_size, device, mode="random")
  593. k_unpad, indices_k, cu_seqlens_k_new, *rest = unpad_input(k, key_new_padding_mask)
  594. v_unpad, *rest = unpad_input(v, key_new_padding_mask)
  595. else:
  596. k_unpad, v_unpad = k, v
  597. else:
  598. k, v, k_unpad, v_unpad = None, None, None, None
  599. if page_size is None:
  600. k_cache = torch.randn(batch_size_cache, seqlen_k, nheads_k, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref)
  601. v_cache = torch.randn(batch_size_cache, seqlen_k, nheads_k, d, device=device, dtype=dtype_ref).to(dtype).to(dtype_ref)
  602. page_table = None
  603. else:
  604. (
  605. k_cache,
  606. v_cache,
  607. page_table,
  608. k_cache_paged,
  609. v_cache_paged,
  610. num_blocks,
  611. ) = _generate_block_kvcache(
  612. seqlen_k, page_size, batch_size_cache, nheads_k, d, device, dtype_ref
  613. )
  614. cache_seqlens = torch.randint(
  615. 0 if new_kv else 1,
  616. # If we don't use seqlen_q in the case of causal and rotary, cos/sin won't be long enough
  617. (
  618. (seqlen_k - (seqlen_q if (causal or local) and rotary_dim > 1 else seqlen_new) + 1)
  619. if new_kv
  620. else (seqlen_k + 1)
  621. ),
  622. (batch_size,),
  623. dtype=torch.int32,
  624. device=device,
  625. )
  626. if has_leftpad:
  627. cache_leftpad = torch.cat([torch.randint(0, cache_seqlens[i].item(), (1,), dtype=torch.int32, device=device)
  628. if cache_seqlens[i].item() > 0 else torch.zeros(1, dtype=torch.int32, device=device)
  629. for i in range(batch_size)])
  630. else:
  631. cache_leftpad = None
  632. if has_batch_idx:
  633. cache_batch_idx = torch.randperm(batch_size_cache, dtype=torch.int32, device=device)[
  634. :batch_size
  635. ]
  636. else:
  637. cache_batch_idx = None
  638. arange = rearrange(torch.arange(seqlen_k, device=device), "s -> 1 s")
  639. cache_seqlens_expanded = rearrange(cache_seqlens, "b -> b 1")
  640. if not new_kv:
  641. key_padding_mask = arange < cache_seqlens_expanded
  642. else:
  643. k_new_seqlens = key_new_padding_mask.sum(-1, keepdims=True) if varlen_q else seqlen_new
  644. key_padding_mask = arange < cache_seqlens_expanded + k_new_seqlens
  645. if has_leftpad:
  646. key_padding_mask = torch.logical_and(
  647. key_padding_mask, arange >= cache_leftpad.unsqueeze(-1).expand(-1, seqlen_k)
  648. )
  649. # cache_seqlens = torch.tensor([64], dtype=torch.int32, device=device)
  650. if rotary_dim > 0:
  651. angle = (
  652. torch.rand(
  653. seqlen_k if page_size is None else num_blocks * page_size,
  654. rotary_dim // 2,
  655. device=device,
  656. )
  657. * 2
  658. * math.pi
  659. )
  660. cos = torch.cos(angle).to(dtype=dtype_ref).to(dtype).to(dtype_ref)
  661. sin = torch.sin(angle).to(dtype=dtype_ref).to(dtype).to(dtype_ref)
  662. if causal or local:
  663. q_ro = apply_rotary_emb(
  664. q, cos, sin, seqlen_offsets=cache_seqlens, interleaved=rotary_interleaved
  665. )
  666. else:
  667. q_ro = rearrange(
  668. apply_rotary_emb(
  669. rearrange(q, "b s h d -> b 1 (s h) d"),
  670. cos,
  671. sin,
  672. seqlen_offsets=cache_seqlens,
  673. interleaved=rotary_interleaved,
  674. ),
  675. "b 1 (s h) d -> b s h d",
  676. s=seqlen_q,
  677. )
  678. # q_ro = q
  679. k_ro = apply_rotary_emb(
  680. k, cos, sin, seqlen_offsets=cache_seqlens, interleaved=rotary_interleaved
  681. )
  682. else:
  683. cos, sin = None, None
  684. q_ro, k_ro = q, k
  685. # k_cache[:, 64:] = -1
  686. k_cache_ref = (k_cache if not has_batch_idx else k_cache[cache_batch_idx]).clone()
  687. v_cache_ref = (v_cache if not has_batch_idx else v_cache[cache_batch_idx]).clone()
  688. if new_kv:
  689. update_mask = torch.logical_and(
  690. cache_seqlens_expanded <= arange, arange < cache_seqlens_expanded + k_new_seqlens
  691. )
  692. k_to_update = rearrange(k_ro, "b s ... -> (b s) ...")
  693. v_to_update = rearrange(v, "b s ... -> (b s) ...")
  694. if varlen_q:
  695. k_to_update = k_to_update[indices_k]
  696. v_to_update = v_to_update[indices_k]
  697. k_cache_ref[update_mask] = k_to_update
  698. v_cache_ref[update_mask] = v_to_update
  699. k_cache_rep = repeat(k_cache_ref, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  700. v_cache_rep = repeat(v_cache_ref, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  701. out_ref, _ = attention_ref(
  702. q_ro,
  703. k_cache_rep,
  704. v_cache_rep,
  705. query_padding_mask,
  706. key_padding_mask,
  707. causal=causal,
  708. window_size=window_size,
  709. key_leftpad=cache_leftpad,
  710. )
  711. out_pt, _ = attention_ref(
  712. q_ro,
  713. k_cache_rep,
  714. v_cache_rep,
  715. query_padding_mask,
  716. key_padding_mask,
  717. causal=causal,
  718. window_size=window_size,
  719. upcast=False,
  720. reorder_ops=True,
  721. key_leftpad=cache_leftpad,
  722. intermediate_dtype=dtype if dtype == torch.float8_e4m3fn else None
  723. )
  724. q = q.to(dtype)
  725. q_unpad = q_unpad.to(dtype) if varlen_q else None
  726. k_cache = k_cache.to(dtype)
  727. v_cache = v_cache.to(dtype)
  728. k_cache_paged = k_cache_paged.to(dtype) if page_size is not None else None
  729. v_cache_paged = v_cache_paged.to(dtype) if page_size is not None else None
  730. k = k.to(dtype) if k is not None else None
  731. v = v.to(dtype) if v is not None else None
  732. k_unpad = k_unpad.to(dtype) if k_unpad is not None else None
  733. v_unpad = v_unpad.to(dtype) if v_unpad is not None else None
  734. cos = cos.to(dtype) if cos is not None else None
  735. sin = sin.to(dtype) if sin is not None else None
  736. out, lse, *rest = flash_attn_with_kvcache(
  737. q if not varlen_q else q_unpad,
  738. k_cache if page_size is None else k_cache_paged,
  739. v_cache if page_size is None else v_cache_paged,
  740. k if not new_kv or not varlen_q else k_unpad,
  741. v if not new_kv or not varlen_q else v_unpad,
  742. rotary_cos=cos,
  743. rotary_sin=sin,
  744. cache_seqlens=cache_seqlens,
  745. cache_batch_idx=cache_batch_idx,
  746. cache_leftpad=cache_leftpad,
  747. page_table=page_table,
  748. cu_seqlens_q=cu_seqlens_q,
  749. cu_seqlens_k_new=cu_seqlens_k_new,
  750. max_seqlen_q=max_seqlen_q,
  751. causal=causal,
  752. window_size=window_size,
  753. rotary_interleaved=rotary_interleaved,
  754. num_splits=num_splits,
  755. return_softmax_lse=True
  756. )
  757. if varlen_q:
  758. out = output_pad_fn(out)
  759. # out = flash_attn_with_kvcache(
  760. # q, k_cache, v_cache, cache_seqlens=cache_seqlens, causal=causal, window_size=window_size
  761. # )
  762. # out = flash_attn_with_kvcache(q, k_cache, v_cache, causal=causal, window_size=window_size)
  763. # qk = torch.einsum("bqhd,bkhd->bhqk", q, k_cache_ref)
  764. # m = qk.amax(-1, keepdim=True)
  765. # s_tmp = torch.exp((qk - m) / math.sqrt(d))
  766. # o1 = torch.einsum('bhst,bthd->bshd', s_tmp, v_cache_ref)
  767. # lse_ref = torch.logsumexp(qk / math.sqrt(d), -1)
  768. # probs = torch.softmax(qk, dim=-1)
  769. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  770. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  771. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  772. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  773. # breakpoint()
  774. # Check that FlashAttention's numerical error is at most twice the numerical error
  775. # of a Pytorch implementation.
  776. if new_kv:
  777. if page_size is None:
  778. k_cache_select = (
  779. k_cache.to(dtype_ref) if not has_batch_idx else k_cache.to(dtype_ref)[cache_batch_idx]
  780. )
  781. v_cache_select = (
  782. v_cache.to(dtype_ref) if not has_batch_idx else v_cache.to(dtype_ref)[cache_batch_idx]
  783. )
  784. else:
  785. k_cache_select = rearrange(
  786. k_cache_paged.to(dtype_ref)[(page_table if not has_batch_idx else page_table[cache_batch_idx]).flatten()],
  787. "(b nblocks) block_size ... -> b (nblocks block_size) ...",
  788. b=batch_size,
  789. )[:, :seqlen_k].to(dtype_ref)
  790. v_cache_select = rearrange(
  791. v_cache_paged.to(dtype_ref)[(page_table if not has_batch_idx else page_table[cache_batch_idx]).flatten()],
  792. "(b nblocks) block_size ... -> b (nblocks block_size) ...",
  793. b=batch_size,
  794. )[:, :seqlen_k].to(dtype_ref)
  795. k_cache_ref = k_cache_ref.to(dtype).to(dtype_ref)
  796. v_cache_ref = v_cache_ref.to(dtype).to(dtype_ref)
  797. if dtype is not torch.float8_e4m3fn:
  798. assert torch.equal(v_cache_select, v_cache_ref)
  799. else:
  800. assert torch.allclose(v_cache_select, v_cache_ref, rtol=1e-3, atol=1e-3)
  801. # breakpoint()
  802. # if rotary_dim == 0 and dtype is not torch.float8_e4m3fn:
  803. if rotary_dim == 0:
  804. assert torch.equal(k_cache_select, k_cache_ref)
  805. else:
  806. # if not torch.allclose(k_cache_select, k_cache_ref, rtol=1e-3, atol=1e-3):
  807. # breakpoint()
  808. if dtype is not torch.float8_e4m3fn:
  809. assert torch.allclose(k_cache_select, k_cache_ref, rtol=1e-3, atol=1e-3)
  810. else:
  811. assert torch.allclose(k_cache_select, k_cache_ref, rtol=1e-1, atol=1e-1)
  812. mult = 4 if dtype == torch.float8_e4m3fn else 2
  813. assert (out - out_ref).abs().max().item() <= mult * (out_pt - out_ref).abs().max().item() + 1e-5
  814. mult_mean = 3 if dtype == torch.float8_e4m3fn else 1.5
  815. assert (out - out_ref).abs().mean().item() <= mult_mean * (out_pt - out_ref).abs().mean().item()
  816. def _generate_block_kvcache(seqlen_k, page_size, batch_size, nheads_k, d, device, dtype):
  817. num_blocks = math.ceil(seqlen_k / page_size) * batch_size * 3
  818. k_cache_paged = torch.randn(
  819. num_blocks, page_size, nheads_k, d, device=device, dtype=dtype
  820. )
  821. v_cache_paged = torch.randn(
  822. num_blocks, page_size, nheads_k, d, device=device, dtype=dtype
  823. )
  824. page_table = rearrange(
  825. torch.randperm(num_blocks, dtype=torch.int32, device=device),
  826. "(b nblocks) -> b nblocks",
  827. b=batch_size,
  828. )
  829. k_cache = rearrange(
  830. k_cache_paged[page_table.flatten()],
  831. "(b nblocks) block_size ... -> b (nblocks block_size) ...",
  832. b=batch_size,
  833. )[:, :seqlen_k]
  834. v_cache = rearrange(
  835. v_cache_paged[page_table.flatten()],
  836. "(b nblocks) block_size ... -> b (nblocks block_size) ...",
  837. b=batch_size,
  838. )[:, :seqlen_k]
  839. return k_cache, v_cache, page_table, k_cache_paged, v_cache_paged, num_blocks
  840. @pytest.mark.parametrize("dtype", [torch.bfloat16])
  841. @pytest.mark.parametrize("causal", [False, True])
  842. # @pytest.mark.parametrize('causal', [False])
  843. @pytest.mark.parametrize('d', [128])
  844. @pytest.mark.parametrize(
  845. "seqlen_q,seqlen_k",
  846. [
  847. (64, 8192),
  848. ],
  849. )
  850. def test_flash_attn_cluster(seqlen_q, seqlen_k, d, causal, dtype):
  851. device = "cuda"
  852. torch.random.manual_seed(0)
  853. batch_size = 2
  854. nheads = 16
  855. nheads_kv = 4
  856. # There was a bug where this would cause "unspecified launch failure" due to Cluster
  857. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype)
  858. k = torch.randn(batch_size, seqlen_k, nheads_kv, d, device=device, dtype=dtype)
  859. v = torch.randn(batch_size, seqlen_k, nheads_kv, d, device=device, dtype=dtype)
  860. for _ in range(100):
  861. flash_attn_func(q, k, v, causal=causal)
  862. # @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  863. @pytest.mark.parametrize("dtype", [torch.bfloat16])
  864. @pytest.mark.parametrize("causal", [False, True])
  865. # @pytest.mark.parametrize('causal', [False])
  866. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  867. # @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128])
  868. # @pytest.mark.parametrize('d', [32, 56, 64, 80, 96, 128])
  869. # @pytest.mark.parametrize("d", [32, 64, 96, 128, 160, 192])
  870. # @pytest.mark.parametrize('d', [80])
  871. @pytest.mark.parametrize(
  872. "seqlen_q,seqlen_k",
  873. [
  874. (1, 239),
  875. (239, 1),
  876. (3, 799),
  877. (799, 3),
  878. (1024, 128),
  879. (97, 97),
  880. (128, 128),
  881. (200, 200),
  882. (256, 256),
  883. (257, 257),
  884. (384, 384),
  885. (512, 512),
  886. (768, 768),
  887. (1024, 1024),
  888. (2048, 2048),
  889. ],
  890. )
  891. def test_flash_attn_race_condition(seqlen_q, seqlen_k, d, causal, dtype):
  892. device = "cuda"
  893. # set seed
  894. torch.random.manual_seed(0)
  895. # Simulate under memory load
  896. dummy = torch.empty(70 * 1024 ** 3, dtype=torch.uint8, device=device)
  897. batch_size = 60 # Sometimes we need large batch size for the race conditions to trigger
  898. nheads = 4
  899. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype, requires_grad=True)
  900. k = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  901. v = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  902. torch.random.manual_seed(42)
  903. out0, lse0 = flash_attn_func(q, k, v, causal=causal)
  904. g = torch.randn_like(out0)
  905. dq0, dk0, dv0 = torch.autograd.grad(out0, (q, k, v), g)
  906. # Numerical error if we just do any arithmetic on dq
  907. dq_atol = 2 * ((dq0 + 0.3 - 0.3) - dq0).abs().max().item()
  908. for i in range(1000):
  909. torch.random.manual_seed(42)
  910. out, lse = flash_attn_func(q, k, v, causal=causal)
  911. assert torch.equal(out, out0)
  912. assert torch.equal(lse, lse0)
  913. dq, dk, dv = torch.autograd.grad(out, (q, k, v), g)
  914. dq_equal = torch.allclose(dq, dq0, atol=dq_atol)
  915. if not dq_equal:
  916. print(f"Iter {i}, {dq_atol = }, dQ max diff: {(dq - dq0).abs().max().item()}")
  917. # breakpoint()
  918. assert torch.equal(dv, dv0)
  919. assert torch.equal(dk, dk0)
  920. assert dq_equal
  921. def attention_combine_ref(out_partial, lse_partial):
  922. """
  923. out_partial: (num_splits, batch_size, seqlen, nheads, d)
  924. lse_partial: (num_splits, batch_size, nheads, seqlen)
  925. """
  926. lse = torch.logsumexp(lse_partial, dim=0)
  927. scale = torch.exp(lse_partial - lse)
  928. scale = torch.where(torch.isinf(scale) | torch.isnan(scale), torch.zeros_like(scale), scale)
  929. out = (scale.unsqueeze(-1) * out_partial).sum(0)
  930. return out, lse
  931. @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
  932. # @pytest.mark.parametrize("dtype", [torch.float32])
  933. # @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  934. @pytest.mark.parametrize("d", [64, 96, 128, 192, 256])
  935. # @pytest.mark.parametrize("d", [128])
  936. @pytest.mark.parametrize("seqlen", [1, 2, 3, 32, 64, 256, 113, 108, 640, 1024, 2048])
  937. # @pytest.mark.parametrize("seqlen", [12, 32, 64, 256, 112, 108, 640, 1024, 2048, 8192])
  938. # @pytest.mark.parametrize("seqlen", [15])
  939. @pytest.mark.parametrize("num_splits", [1, 2, 3, 5, 17, 32, 55, 97, 155])
  940. # @pytest.mark.parametrize("num_splits", [1, 2, 3, 5, 11])
  941. # @pytest.mark.parametrize("num_splits", [128])
  942. def test_flash_attn_combine(num_splits, seqlen, d, dtype):
  943. if DISABLE_SPLIT:
  944. pytest.skip()
  945. device = "cuda"
  946. # set seed
  947. torch.random.manual_seed(1)
  948. batch_size = 5
  949. nheads = 16
  950. # batch_size = 1
  951. # nheads = 1
  952. out_partial = torch.randn(num_splits * 2, batch_size, nheads, seqlen, d, device=device, dtype=torch.float32).transpose(2, 3)[:num_splits] # To test non-contiguous tensor
  953. lse_partial = torch.randn(num_splits, batch_size, nheads * 2, seqlen, device=device, dtype=torch.float32).transpose(-1, -2)[:, :, :, :nheads] # To test non-contiguous tensor
  954. # To test short-circuiting based on num_splits
  955. lse_partial[num_splits // 2:, :batch_size // 3] = -float("inf")
  956. out, lse = flash_attn_combine(out_partial, lse_partial, out_dtype=dtype)
  957. out_ref, lse_ref = attention_combine_ref(out_partial, lse_partial)
  958. out_pt = out_ref.to(dtype)
  959. print(f"LSE max diff: {(lse - lse_ref).abs().max().item()}")
  960. print(f"LSE mean diff: {(lse - lse_ref).abs().mean().item()}")
  961. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  962. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  963. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  964. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  965. # breakpoint()
  966. assert torch.allclose(lse, lse_ref, atol=1e-5, rtol=1e-5)
  967. multiple = 2
  968. assert ((out - out_ref).abs().max().item() <= multiple * (out_pt - out_ref).abs().max().item()) or torch.allclose(out, out_pt, atol=1e-5, rtol=1e-5)
  969. # from flash_attn.utils.benchmark import pytorch_profiler
  970. # # pytorch_profiler(torch.sum, lse_partial)
  971. # pytorch_profiler(flash_attn_combine, out_partial, lse_partial)
  972. # pytorch_profiler(torch.sum, out_partial)