1
0

test_flash_attn.py 44 KB

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