test_flash_attn.py 50 KB

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