test_flash_attn.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. import math
  2. import pytest
  3. import torch
  4. import torch.nn.functional as F
  5. from einops import rearrange, repeat
  6. from flash_attn import (
  7. flash_attn_func,
  8. flash_attn_kvpacked_func,
  9. flash_attn_qkvpacked_func,
  10. flash_attn_varlen_func,
  11. flash_attn_varlen_kvpacked_func,
  12. flash_attn_varlen_qkvpacked_func,
  13. flash_attn_with_kvcache,
  14. )
  15. from flash_attn.bert_padding import pad_input, unpad_input
  16. from flash_attn.flash_attn_interface import _get_block_size
  17. from flash_attn.layers.rotary import apply_rotary_emb
  18. MAX_HEADDIM_SM8x = 192
  19. is_sm75 = torch.cuda.get_device_capability("cuda") == (7, 5)
  20. is_sm8x = torch.cuda.get_device_capability("cuda")[0] == 8
  21. is_sm80 = torch.cuda.get_device_capability("cuda") == (8, 0)
  22. is_sm90 = torch.cuda.get_device_capability("cuda") == (9, 0)
  23. def generate_random_padding_mask(max_seqlen, batch_size, device, mode="random"):
  24. assert mode in ["full", "random", "third"]
  25. if mode == "full":
  26. lengths = torch.full((batch_size, 1), max_seqlen, device=device, dtype=torch.int32)
  27. elif mode == "random":
  28. lengths = torch.randint(
  29. max(1, max_seqlen - 20), max_seqlen + 1, (batch_size, 1), device=device
  30. )
  31. elif mode == "third":
  32. lengths = torch.randint(max_seqlen // 3, max_seqlen + 1, (batch_size, 1), device=device)
  33. padding_mask = (
  34. repeat(torch.arange(max_seqlen, device=device), "s -> b s", b=batch_size) < lengths
  35. )
  36. return padding_mask
  37. def generate_qkv(
  38. q, k, v, query_padding_mask=None, key_padding_mask=None, kvpacked=False, qkvpacked=False
  39. ):
  40. """
  41. Arguments:
  42. q: (batch_size, seqlen_q, nheads, d)
  43. k: (batch_size, seqlen_k, nheads_k, d)
  44. v: (batch_size, seqlen_k, nheads_k, d)
  45. query_padding_mask: (batch_size, seqlen), bool
  46. key_padding_mask: (batch_size, seqlen), bool
  47. """
  48. assert not (kvpacked and qkvpacked)
  49. batch_size, seqlen_q, nheads, d = q.shape
  50. _, seqlen_k, nheads_k, _ = k.shape
  51. assert k.shape == (batch_size, seqlen_k, nheads_k, d)
  52. assert v.shape == (batch_size, seqlen_k, nheads_k, d)
  53. if query_padding_mask is not None:
  54. q_unpad, indices_q, cu_seqlens_q, max_seqlen_q = unpad_input(q, query_padding_mask)
  55. output_pad_fn = lambda output_unpad: pad_input(
  56. output_unpad, indices_q, batch_size, seqlen_q
  57. )
  58. else:
  59. q_unpad = rearrange(q, "b s h d -> (b s) h d")
  60. cu_seqlens_q = torch.arange(
  61. 0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int32, device=q_unpad.device
  62. )
  63. max_seqlen_q = seqlen_q
  64. output_pad_fn = lambda output_unpad: rearrange(
  65. output_unpad, "(b s) h d -> b s h d", b=batch_size
  66. )
  67. if key_padding_mask is not None:
  68. k_unpad, indices_k, cu_seqlens_k, max_seqlen_k = unpad_input(k, key_padding_mask)
  69. v_unpad, _, _, _ = unpad_input(v, key_padding_mask)
  70. else:
  71. k_unpad = rearrange(k, "b s h d -> (b s) h d")
  72. v_unpad = rearrange(v, "b s h d -> (b s) h d")
  73. cu_seqlens_k = torch.arange(
  74. 0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int32, device=k_unpad.device
  75. )
  76. max_seqlen_k = seqlen_k
  77. if qkvpacked:
  78. assert (query_padding_mask == key_padding_mask).all()
  79. assert nheads == nheads_k
  80. qkv_unpad = torch.stack([q_unpad, k_unpad, v_unpad], dim=1)
  81. qkv = torch.stack([q, k, v], dim=2)
  82. if query_padding_mask is not None:
  83. dqkv_pad_fn = lambda dqkv_unpad: pad_input(dqkv_unpad, indices_q, batch_size, seqlen_q)
  84. else:
  85. dqkv_pad_fn = lambda dqkv_unpad: rearrange(
  86. dqkv_unpad, "(b s) t h d -> b s t h d", b=batch_size
  87. )
  88. return (
  89. qkv_unpad.detach().requires_grad_(),
  90. cu_seqlens_q,
  91. max_seqlen_q,
  92. qkv.detach().requires_grad_(),
  93. output_pad_fn,
  94. dqkv_pad_fn,
  95. )
  96. elif kvpacked:
  97. kv_unpad = torch.stack([k_unpad, v_unpad], dim=1)
  98. kv = torch.stack([k, v], dim=2)
  99. dq_pad_fn = output_pad_fn
  100. if key_padding_mask is not None:
  101. dkv_pad_fn = lambda dkv_unpad: pad_input(dkv_unpad, indices_k, batch_size, seqlen_k)
  102. else:
  103. dkv_pad_fn = lambda dkv_unpad: rearrange(
  104. dkv_unpad, "(b s) t h d -> b s t h d", b=batch_size
  105. )
  106. return (
  107. q_unpad.detach().requires_grad_(),
  108. kv_unpad.detach().requires_grad_(),
  109. cu_seqlens_q,
  110. cu_seqlens_k,
  111. max_seqlen_q,
  112. max_seqlen_k,
  113. q.detach().requires_grad_(),
  114. kv.detach().requires_grad_(),
  115. output_pad_fn,
  116. dq_pad_fn,
  117. dkv_pad_fn,
  118. )
  119. else:
  120. dq_pad_fn = output_pad_fn
  121. if key_padding_mask is not None:
  122. dk_pad_fn = lambda dk_unpad: pad_input(dk_unpad, indices_k, batch_size, seqlen_k)
  123. else:
  124. dk_pad_fn = lambda dk_unpad: rearrange(dk_unpad, "(b s) h d -> b s h d", b=batch_size)
  125. return (
  126. q_unpad.detach().requires_grad_(),
  127. k_unpad.detach().requires_grad_(),
  128. v_unpad.detach().requires_grad_(),
  129. cu_seqlens_q,
  130. cu_seqlens_k,
  131. max_seqlen_q,
  132. max_seqlen_k,
  133. q.detach().requires_grad_(),
  134. k.detach().requires_grad_(),
  135. v.detach().requires_grad_(),
  136. output_pad_fn,
  137. dq_pad_fn,
  138. dk_pad_fn,
  139. )
  140. def construct_causal_mask(
  141. seqlen_q, seqlen_k, query_padding_mask=None, key_padding_mask=None, device=None
  142. ):
  143. row_idx = rearrange(torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1")
  144. col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long)
  145. sk = (
  146. seqlen_k
  147. if key_padding_mask is None
  148. else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1")
  149. )
  150. sq = (
  151. seqlen_q
  152. if query_padding_mask is None
  153. else rearrange(query_padding_mask.sum(-1), "b -> b 1 1 1")
  154. )
  155. return col_idx > row_idx + sk - sq
  156. def attention_ref(
  157. q,
  158. k,
  159. v,
  160. query_padding_mask=None,
  161. key_padding_mask=None,
  162. dropout_p=0.0,
  163. dropout_mask=None,
  164. causal=False,
  165. upcast=True,
  166. reorder_ops=False,
  167. ):
  168. """
  169. Arguments:
  170. q: (batch_size, seqlen_q, nheads, head_dim)
  171. k: (batch_size, seqlen_k, nheads_k, head_dim)
  172. v: (batch_size, seqlen_k, nheads_k, head_dim)
  173. query_padding_mask: (batch_size, seqlen_q)
  174. key_padding_mask: (batch_size, seqlen_k)
  175. dropout_p: float
  176. dropout_mask: (batch_size, nheads, seqlen_q, seqlen_k)
  177. upcast: whether to cast all inputs to fp32, do all computation in fp32, then cast
  178. output back to fp16/bf16.
  179. reorder_ops: whether to change the order of operations (scaling k instead of scaling k, etc.)
  180. without changing the math. This is to estimate the numerical error from operation
  181. reordering.
  182. Output:
  183. output: (batch_size, seqlen_q, nheads, head_dim)
  184. attention: (batch_size, nheads, seqlen_q, seqlen_k), softmax after dropout
  185. """
  186. dtype_og = q.dtype
  187. if upcast:
  188. q, k, v = q.float(), k.float(), v.float()
  189. seqlen_q, seqlen_k = q.shape[1], k.shape[1]
  190. k = repeat(k, "b s h d -> b s (h g) d", g=q.shape[2] // k.shape[2])
  191. v = repeat(v, "b s h d -> b s (h g) d", g=q.shape[2] // v.shape[2])
  192. d = q.shape[-1]
  193. if not reorder_ops:
  194. scores = torch.einsum("bthd,bshd->bhts", q / math.sqrt(d), k)
  195. else:
  196. scores = torch.einsum("bthd,bshd->bhts", q, k / math.sqrt(d))
  197. if key_padding_mask is not None:
  198. scores.masked_fill_(rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf"))
  199. if causal:
  200. # causal_mask = torch.triu(
  201. # torch.ones(seqlen_q, seqlen_k, dtype=torch.bool, device=q.device), 1
  202. # )
  203. causal_mask = construct_causal_mask(
  204. seqlen_q, seqlen_k, query_padding_mask, key_padding_mask, q.device
  205. )
  206. scores.masked_fill_(causal_mask, float("-inf"))
  207. attention = torch.softmax(scores, dim=-1)
  208. if causal: # Some rows are completely masked out so we fill them with zero instead of NaN
  209. attention = attention.masked_fill(torch.all(causal_mask, dim=-1, keepdim=True), 0.0)
  210. dropout_scaling = 1.0 / (1 - dropout_p)
  211. # attention_drop = attention.masked_fill(~dropout_mask, 0.0) * dropout_scaling
  212. # output = torch.einsum('bhts,bshd->bthd', attention_drop , v)
  213. if dropout_mask is not None:
  214. attention_drop = attention.masked_fill(~dropout_mask, 0.0)
  215. else:
  216. attention_drop = attention
  217. output = torch.einsum("bhts,bshd->bthd", attention_drop, v * dropout_scaling)
  218. if query_padding_mask is not None:
  219. output.masked_fill_(rearrange(~query_padding_mask, "b s -> b s 1 1"), 0.0)
  220. attention = attention.masked_fill(rearrange(~query_padding_mask, "b s -> b 1 s 1"), 0.0)
  221. return output.to(dtype=dtype_og), attention.to(dtype=dtype_og)
  222. def attention_kvpacked_ref(
  223. q,
  224. kv,
  225. query_padding_mask=None,
  226. key_padding_mask=None,
  227. dropout_p=0.0,
  228. dropout_mask=None,
  229. causal=False,
  230. upcast=True,
  231. reorder_ops=False,
  232. ):
  233. return attention_ref(
  234. q,
  235. kv[:, :, 0],
  236. kv[:, :, 1],
  237. query_padding_mask,
  238. key_padding_mask,
  239. dropout_p,
  240. dropout_mask,
  241. upcast=upcast,
  242. causal=causal,
  243. reorder_ops=reorder_ops,
  244. )
  245. def attention_qkvpacked_ref(
  246. qkv,
  247. key_padding_mask=None,
  248. dropout_p=0.0,
  249. dropout_mask=None,
  250. causal=False,
  251. upcast=True,
  252. reorder_ops=False,
  253. ):
  254. return attention_ref(
  255. qkv[:, :, 0],
  256. qkv[:, :, 1],
  257. qkv[:, :, 2],
  258. key_padding_mask,
  259. key_padding_mask,
  260. dropout_p,
  261. dropout_mask,
  262. upcast=upcast,
  263. causal=causal,
  264. reorder_ops=reorder_ops,
  265. )
  266. def generate_sparsity_mask(seqlen, sparsity=0.3):
  267. repeats = seqlen // 16 // 2
  268. # mask = torch.stack([torch.tensor([1, 0] * repeats, dtype=torch.bool, device='cuda'),
  269. # torch.tensor([0, 1] * repeats, dtype=torch.bool, device='cuda')], dim=-1)
  270. # mask = torch.stack([torch.tensor([1, 1] * repeats, dtype=torch.bool, device='cuda'),
  271. # torch.tensor([1, 1] * repeats, dtype=torch.bool, device='cuda')], dim=-1)
  272. # mask = torch.stack([torch.tensor([1, 1] * repeats, dtype=torch.bool, device='cuda')], dim=-1)
  273. # mask = torch.stack([torch.tensor([1, 0] * repeats, dtype=torch.bool, device='cuda')], dim=-1)
  274. nrow, ncol = seqlen // 16, seqlen // 256
  275. mask = torch.rand(nrow, ncol, device="cuda") < sparsity
  276. return mask
  277. def attention_blocksparse_ref(qkv, blockmask, attn_mask, dropout_p, dropout_mask):
  278. """
  279. Arguments:
  280. qkv: (batch_size, seqlen, 3, nheads, head_dim)
  281. blockmask: (seqlen / 16, seqlen / 256)
  282. attn_mask: (batch_size, seqlen)
  283. dropout_p: float
  284. dropout_mask: (batch_size, nheads, seqlen, seqlen)
  285. Output:
  286. output: (batch_size, seqlen, nheads, head_dim)
  287. attention: softmax after dropout
  288. """
  289. q, k, v = qkv.float().unbind(dim=2)
  290. d = qkv.shape[-1]
  291. seqlen = qkv.shape[1]
  292. scores = torch.einsum("bthd,bshd->bhts", q / math.sqrt(d), k)
  293. scores.masked_fill_(rearrange(~attn_mask, "b s -> b 1 1 s"), float("-inf"))
  294. blockmask = repeat(blockmask, "s_16 s_256 -> (s_16 16) (s_256 256)")
  295. blockmask = blockmask[:seqlen, :seqlen]
  296. scores.masked_fill_(rearrange(~blockmask, "t s -> 1 1 t s"), float("-inf"))
  297. attention = torch.softmax(scores, dim=-1)
  298. attention = attention.masked_fill(rearrange(~attn_mask, "b s -> b 1 s 1"), 0.0)
  299. attention = attention.masked_fill_(rearrange(~blockmask, "t s -> 1 1 t s"), 0.0)
  300. attention_drop = attention.masked_fill(~dropout_mask, 0.0) / (1 - dropout_p)
  301. output = torch.einsum("bhts,bshd->bthd", attention_drop, v)
  302. output.masked_fill_(rearrange(~attn_mask, "b s -> b s 1 1"), 0)
  303. return output.to(dtype=qkv.dtype), attention.to(dtype=qkv.dtype)
  304. def convert_flash_attn_S_to_softmax(
  305. S, seqlen_q, seqlen_k, query_padding_mask, key_padding_mask, head_dim, is_dropout, causal=False
  306. ):
  307. """FlashAttention stores the S matrix in a different way.
  308. Arguments:
  309. S: (batch_size, nheads, seqlen_q_rounded, seqlen_k_rounded)
  310. query_padding_mask: (batch_size, seqlen_q_rounded)
  311. key_padding_mask: (batch_size, seqlen_k_rounded)
  312. """
  313. seqlen_q_rounded, seqlen_k_rounded = S.shape[-2:]
  314. warps_n = 4
  315. blocksize_m, blocksize_n = _get_block_size(S.device, head_dim, is_dropout, causal)
  316. nblocks_n = (seqlen_k_rounded + blocksize_n - 1) // blocksize_n
  317. nblocks_m = (seqlen_q_rounded + blocksize_m - 1) // blocksize_m
  318. mmas_n = (blocksize_n + 16 - 1) // 16
  319. S_flat = rearrange(
  320. S,
  321. "b h (nblocks_m blocksize_m) (nblocks_n blocksize_n) -> b h nblocks_m nblocks_n (blocksize_m blocksize_n)",
  322. blocksize_m=blocksize_m,
  323. blocksize_n=blocksize_n,
  324. )
  325. S_converted = rearrange(
  326. S_flat,
  327. "b h nblocks_m nblocks_n (mmas_n mmas_m warps_n eight four c2 c1 c0) -> b h (nblocks_m mmas_m warps_n c1 eight) (nblocks_n mmas_n c2 four c0)",
  328. mmas_n=mmas_n,
  329. warps_n=warps_n,
  330. eight=8,
  331. c0=2,
  332. c1=2,
  333. c2=2,
  334. four=4,
  335. )
  336. if causal:
  337. # causal_mask = torch.triu(
  338. # torch.ones(seqlen_q_rounded, seqlen_k_rounded, dtype=torch.bool, device=q.device), 1
  339. # )
  340. causal_mask = construct_causal_mask(
  341. seqlen_q, seqlen_k, query_padding_mask, key_padding_mask, S.device
  342. )
  343. causal_mask = F.pad(
  344. causal_mask,
  345. (0, seqlen_k_rounded - seqlen_k, 0, seqlen_q_rounded - seqlen_q),
  346. value=True,
  347. )
  348. S_converted.masked_fill_(causal_mask, 0.0)
  349. # Need to zero out things not in attention_mask in case S was initialized with random values
  350. # and some of those values aren't overwritten.
  351. seqlen_q_og = (
  352. query_padding_mask.shape[-1] if query_padding_mask is not None else seqlen_q_rounded
  353. )
  354. if query_padding_mask is not None:
  355. query_padding_mask = F.pad(query_padding_mask, (0, seqlen_q_rounded - seqlen_q_og))
  356. S_converted = S_converted.masked_fill(rearrange(~query_padding_mask, "b s -> b 1 s 1"), 0.0)
  357. seqlen_k_og = key_padding_mask.shape[-1] if key_padding_mask is not None else seqlen_k
  358. if key_padding_mask is not None:
  359. key_padding_mask = F.pad(key_padding_mask, (0, seqlen_k_rounded - seqlen_k_og))
  360. S_converted = S_converted.masked_fill(rearrange(~key_padding_mask, "b s -> b 1 1 s"), 0.0)
  361. S_converted = F.pad(S_converted, (0, 0, 0, seqlen_q_og - seqlen_q_rounded))
  362. S_converted = F.pad(S_converted, (0, seqlen_k_og - seqlen_k_rounded))
  363. return S_converted[:, :, :seqlen_q, :seqlen_k]
  364. def normalize_flash_attn_S(
  365. attn_unnorm,
  366. q,
  367. k,
  368. v,
  369. query_padding_mask=None,
  370. key_padding_mask=None,
  371. is_dropout=False,
  372. causal=False,
  373. ):
  374. """
  375. Arguments:
  376. q: (batch_size, seqlen_q, nheads, head_dim)
  377. k, v: (batch_size, seqlen_k, nheads, head_dim)
  378. key_padding_mask: (batch_size, seqlen_q)
  379. Output:
  380. softmax_lse: (batch_size, nheads, seqlen_q)
  381. softmax_max: (batch_size, nheads, seqlen_q)
  382. """
  383. q, k, v = q.float(), k.float(), v.float()
  384. _, seqlen_q, _, head_dim = q.shape
  385. seqlen_k = k.shape[1]
  386. scores = torch.einsum("bthd,bshd->bhts", q / math.sqrt(head_dim), k)
  387. if key_padding_mask is not None:
  388. scores.masked_fill_(rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf"))
  389. if causal:
  390. # causal_mask = torch.triu(
  391. # torch.ones(seqlen_q, seqlen_k, dtype=torch.bool, device=q.device), 1
  392. # )
  393. causal_mask = construct_causal_mask(
  394. seqlen_q, seqlen_k, query_padding_mask, key_padding_mask, q.device
  395. )
  396. scores.masked_fill_(causal_mask, float("-inf"))
  397. _, block_size_n = _get_block_size(scores.device, head_dim, is_dropout, causal)
  398. scores_block = scores.split(block_size_n, dim=-1)
  399. lse_block = torch.stack([torch.logsumexp(s, dim=-1) for s in scores_block], dim=-1)
  400. lse = torch.logsumexp(lse_block, dim=-1)
  401. # lse could be -inf (i.e. all values in scores are -inf), and we want to set those to inf
  402. # so that when we do torch.exp(m - lse), we get 0.0 instead of NaN.
  403. lse[lse == float("-inf")] = float("inf")
  404. scores_max_block = torch.stack([torch.amax(s, dim=-1) for s in scores_block], dim=-1)
  405. cummax_block = torch.cummax(scores_max_block.flip(-1), dim=-1).values.flip(-1).unbind(dim=-1)
  406. attn_unnorm_block = attn_unnorm.split(block_size_n, dim=-1)
  407. attn_norm = torch.cat(
  408. [
  409. a * rearrange(torch.exp(m - lse), "b h s -> b h s 1")
  410. for a, m in zip(attn_unnorm_block, cummax_block)
  411. ],
  412. dim=-1,
  413. )
  414. if query_padding_mask is not None:
  415. attn_norm.masked_fill_(rearrange(~query_padding_mask, "b s -> b 1 s 1"), 0.0)
  416. return attn_norm.to(dtype=attn_unnorm.dtype)
  417. def get_dropout_fraction(
  418. dropout_mask, query_padding_mask=None, key_padding_mask=None, causal=False
  419. ):
  420. """
  421. dropout_mask: (batch_size, nheads, seqlen_q, seqlen_k), bool. True means keep, False means drop.
  422. query_padding_mask: (batch_size, seqlen_q)
  423. key_padding_mask: (batch_size, seqlen_k)
  424. """
  425. batch_size, nheads, seqlen_q, seqlen_k = dropout_mask.shape
  426. dropped = ~dropout_mask
  427. if query_padding_mask is not None:
  428. dropped.masked_fill_(rearrange(~query_padding_mask, "b s -> b 1 s 1"), False)
  429. if key_padding_mask is not None:
  430. dropped.masked_fill_(rearrange(~key_padding_mask, "b s -> b 1 1 s"), False)
  431. if causal:
  432. # causal_mask = torch.triu(
  433. # torch.ones(seqlen_q, seqlen_k, dtype=torch.bool, device=dropout_mask.device), 1
  434. # )
  435. causal_mask = construct_causal_mask(
  436. seqlen_q, seqlen_k, query_padding_mask, key_padding_mask, dropout_mask.device
  437. )
  438. dropped.masked_fill_(causal_mask, False)
  439. dropped_total = dropped.sum()
  440. query_lengths = (
  441. query_padding_mask.sum(dim=-1)
  442. if query_padding_mask is not None
  443. else torch.full((batch_size,), seqlen_q, device=dropout_mask.device)
  444. )
  445. key_lengths = (
  446. key_padding_mask.sum(dim=-1)
  447. if key_padding_mask is not None
  448. else torch.full((batch_size,), seqlen_k, device=dropout_mask.device)
  449. )
  450. if not causal:
  451. numel_per_batch = query_lengths * key_lengths
  452. else:
  453. numel_per_batch = torch.where(
  454. key_lengths <= query_lengths,
  455. key_lengths * (key_lengths + 1) / 2,
  456. query_lengths * key_lengths - (query_lengths * (query_lengths - 1) / 2),
  457. )
  458. return dropped_total / (numel_per_batch.sum() * nheads)
  459. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  460. # @pytest.mark.parametrize('dtype', [torch.float16])
  461. @pytest.mark.parametrize("causal", [False, True])
  462. # @pytest.mark.parametrize('causal', [True])
  463. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  464. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192, 224, 256])
  465. # @pytest.mark.parametrize('d', [32, 64, 96, 128])
  466. # @pytest.mark.parametrize('d', [64])
  467. # @pytest.mark.parametrize('seqlen', [128, 256, 384, 512, 768, 1024, 2048])
  468. @pytest.mark.parametrize("seqlen", [97, 128, 200, 256, 257, 384, 512, 768, 1024, 1025, 2048])
  469. # @pytest.mark.parametrize('seqlen', [97])
  470. @pytest.mark.parametrize("dropout_p", [0.0, 0.17])
  471. # @pytest.mark.parametrize('dropout_p', [0.17])
  472. def test_flash_attn_qkvpacked(seqlen, d, dropout_p, causal, dtype):
  473. if seqlen >= 2048 and torch.cuda.get_device_properties("cuda").total_memory <= 16 * 2**30:
  474. pytest.skip() # Reference implementation OOM
  475. device = "cuda"
  476. # set seed
  477. torch.random.manual_seed(0)
  478. batch_size = 16
  479. nheads = 9
  480. qkv = torch.randn(
  481. batch_size, seqlen, 3, nheads, d, device=device, dtype=dtype, requires_grad=True
  482. )
  483. out, lse, S_dmask = flash_attn_qkvpacked_func(
  484. qkv, dropout_p, return_attn_probs=True, causal=causal
  485. )
  486. if dropout_p > 0.0:
  487. S_dmask_converted = convert_flash_attn_S_to_softmax(
  488. S_dmask, seqlen, seqlen, None, None, d, dropout_p > 0.0, causal=causal
  489. )
  490. dropout_mask = S_dmask_converted >= 0
  491. attn_unnorm = S_dmask_converted.abs()
  492. attn = normalize_flash_attn_S(
  493. attn_unnorm,
  494. qkv[:, :, 0],
  495. qkv[:, :, 1],
  496. qkv[:, :, 2],
  497. None,
  498. None,
  499. dropout_p > 0.0,
  500. causal=causal,
  501. )
  502. dropout_fraction = get_dropout_fraction(dropout_mask, None, None, causal=causal).item()
  503. print(f"Actual dropout fraction: {dropout_fraction}")
  504. else:
  505. dropout_mask = None
  506. out_ref, attn_ref = attention_qkvpacked_ref(qkv, None, dropout_p, dropout_mask, causal=causal)
  507. out_pt, attn_pt = attention_qkvpacked_ref(
  508. qkv, None, dropout_p, dropout_mask, causal=causal, upcast=False, reorder_ops=True
  509. )
  510. # v = qkv[:, :, 2].float()
  511. # qk = torch.einsum('bshd,bthd->bhst', qkv[:, :, 0], qkv[:, :, 1]).float()
  512. # if causal:
  513. # causal_mask = torch.triu(torch.ones(seqlen, seqlen, dtype=torch.bool, device=qkv.device), 1)
  514. # qk.masked_fill_(causal_mask, float('-inf'))
  515. # m = qk.amax(-1, keepdim=True)
  516. # s_tmp = torch.exp((qk - m) / math.sqrt(d))
  517. # p_tmp = torch.softmax(qk / math.sqrt(d), -1)
  518. # p_dropped = p_tmp if dropout_mask is None else p_tmp.masked_fill(~dropout_mask, 0)
  519. # lse_ref = torch.logsumexp(qk / math.sqrt(d), -1)
  520. # qk_max1 = torch.max(qk[:, :, 128:, 192:], -1, keepdim=True).values
  521. # qk_max2 = torch.max(qk[:, :, 128:, 128:], -1, keepdim=True).values
  522. # qk_max3 = torch.max(qk[:, :, 128:, 64:], -1, keepdim=True).values
  523. # qk_max4 = torch.max(qk[:, :, 128:, :], -1, keepdim=True).values
  524. # o1 = torch.einsum('bhst,bthd->bshd', torch.exp((qk[:, :, 128:, 192:] - qk_max1) / math.sqrt(d)), v[:, 192:])
  525. # o2 = torch.einsum('bhst,bthd->bshd', torch.exp((qk[:, :, 128:, 128:] - qk_max2) / math.sqrt(d)), v[:, 128:])
  526. # o3 = torch.einsum('bhst,bthd->bshd', torch.exp((qk[:, :, 128:, 64:] - qk_max3) / math.sqrt(d)), v[:, 64:])
  527. # o4 = torch.einsum('bhst,bthd->bshd', torch.exp((qk[:, :, 128:, :] - qk_max4) / math.sqrt(d)), v[:, :])
  528. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  529. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  530. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  531. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  532. if dropout_p > 0.0:
  533. print(f"Attention max diff: {(attn - attn_ref).abs().max().item()}")
  534. print(f"Attention Pytorch max diff: {(attn_pt - attn_ref).abs().max().item()}")
  535. g = torch.randn_like(out)
  536. # do_o = (g.float() * out.float()).sum(-1)
  537. # dv_tmp = torch.einsum('bhts,bthd->bshd', attn_pt[:, :, :64], g[:, :64])
  538. # dv_tmp1 = torch.einsum('bhts,bthd->bshd', attn_pt[:, :, 64:], g[:, 64:])
  539. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  540. (dqkv,) = torch.autograd.grad(out, qkv, g)
  541. (dqkv_ref,) = torch.autograd.grad(out_ref, qkv, g)
  542. (dqkv_pt,) = torch.autograd.grad(out_pt, qkv, g)
  543. print(f"dQ max diff: {(dqkv[:, :, 0] - dqkv_ref[:, :, 0]).abs().max().item()}")
  544. print(f"dK max diff: {(dqkv[:, :, 1] - dqkv_ref[:, :, 1]).abs().max().item()}")
  545. print(f"dV max diff: {(dqkv[:, :, 2] - dqkv_ref[:, :, 2]).abs().max().item()}")
  546. print(f"dQKV mean diff: {(dqkv - dqkv_ref).abs().mean().item()}")
  547. print(f"dQ Pytorch max diff: {(dqkv_pt[:, :, 0] - dqkv_ref[:, :, 0]).abs().max().item()}")
  548. print(f"dK Pytorch max diff: {(dqkv_pt[:, :, 1] - dqkv_ref[:, :, 1]).abs().max().item()}")
  549. print(f"dV Pytorch max diff: {(dqkv_pt[:, :, 2] - dqkv_ref[:, :, 2]).abs().max().item()}")
  550. print(f"dQKV Pytorch mean diff: {(dqkv_pt - dqkv_ref).abs().mean().item()}")
  551. # Check that FlashAttention's numerical error is at most twice the numerical error
  552. # of a Pytorch implementation.
  553. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item()
  554. if dropout_p > 0.0:
  555. assert (attn - attn_ref).abs().max().item() <= 2 * (attn_pt - attn_ref).abs().max().item()
  556. assert abs(dropout_fraction - dropout_p) <= 0.01
  557. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  558. assert (dqkv - dqkv_ref).abs().max().item() <= 2 * (dqkv_pt - dqkv_ref).abs().max().item()
  559. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  560. # @pytest.mark.parametrize('dtype', [torch.float16])
  561. @pytest.mark.parametrize("causal", [False, True])
  562. # @pytest.mark.parametrize('causal', [False])
  563. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  564. # @pytest.mark.parametrize('d', [64])
  565. @pytest.mark.parametrize("seqlen", [97, 128, 200, 256, 257, 384, 512, 768, 1024, 1025, 2048])
  566. # @pytest.mark.parametrize('seqlen', [128])
  567. @pytest.mark.parametrize("dropout_p", [0.0, 0.17])
  568. # @pytest.mark.parametrize('dropout_p', [0.0])
  569. def test_flash_attn_varlen_qkvpacked(seqlen, d, dropout_p, causal, dtype):
  570. if seqlen >= 2048 and torch.cuda.get_device_properties("cuda").total_memory <= 16 * 2**30:
  571. pytest.skip() # Reference implementation OOM
  572. device = "cuda"
  573. # set seed
  574. torch.random.manual_seed(0)
  575. batch_size = 5
  576. nheads = 6
  577. qkv = torch.randn(
  578. batch_size, seqlen, 3, nheads, d, device=device, dtype=dtype, requires_grad=True
  579. )
  580. key_padding_mask = generate_random_padding_mask(seqlen, batch_size, device, mode="random")
  581. # key_padding_mask = generate_random_padding_mask(seqlen, batch_size, device, mode='full')
  582. qkv_unpad, cu_seqlens, max_seqlen, qkv, output_pad_fn, dqkv_pad_fn = generate_qkv(
  583. *qkv.unbind(dim=2), key_padding_mask, key_padding_mask, qkvpacked=True
  584. )
  585. out_unpad, sm_lse, S_dmask = flash_attn_varlen_qkvpacked_func(
  586. qkv_unpad, cu_seqlens, max_seqlen, dropout_p, return_attn_probs=True, causal=causal
  587. )
  588. out = output_pad_fn(out_unpad)
  589. if dropout_p > 0.0:
  590. S_dmask_converted = convert_flash_attn_S_to_softmax(
  591. S_dmask,
  592. seqlen,
  593. seqlen,
  594. key_padding_mask,
  595. key_padding_mask,
  596. d,
  597. dropout_p > 0.0,
  598. causal=causal,
  599. )
  600. dropout_mask = S_dmask_converted >= 0
  601. attn_unnorm = S_dmask_converted.abs()
  602. attn = normalize_flash_attn_S(
  603. attn_unnorm,
  604. qkv[:, :, 0],
  605. qkv[:, :, 1],
  606. qkv[:, :, 2],
  607. key_padding_mask,
  608. key_padding_mask,
  609. dropout_p > 0.0,
  610. causal=causal,
  611. )
  612. dropout_fraction = get_dropout_fraction(
  613. dropout_mask, key_padding_mask, key_padding_mask, causal=causal
  614. ).item()
  615. print(f"Actual dropout fraction: {dropout_fraction}")
  616. else:
  617. dropout_mask = None
  618. out_ref, attn_ref = attention_qkvpacked_ref(
  619. qkv, key_padding_mask, dropout_p, dropout_mask, causal=causal
  620. )
  621. out_pt, attn_pt = attention_qkvpacked_ref(
  622. qkv,
  623. key_padding_mask,
  624. dropout_p,
  625. dropout_mask,
  626. causal=causal,
  627. upcast=False,
  628. reorder_ops=True,
  629. )
  630. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  631. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  632. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  633. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  634. if dropout_p > 0.0:
  635. print(f"Attention max diff: {(attn - attn_ref).abs().max().item()}")
  636. print(f"Attention Pytorch max diff: {(attn_pt - attn_ref).abs().max().item()}")
  637. g = torch.randn_like(out)
  638. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  639. (dqkv_unpad,) = torch.autograd.grad(out, qkv_unpad, g)
  640. dqkv = dqkv_pad_fn(dqkv_unpad)
  641. (dqkv_ref,) = torch.autograd.grad(out_ref, qkv, g)
  642. (dqkv_pt,) = torch.autograd.grad(out_pt, qkv, g)
  643. print(f"dQ max diff: {(dqkv[:, :, 0] - dqkv_ref[:, :, 0]).abs().max().item()}")
  644. print(f"dK max diff: {(dqkv[:, :, 1] - dqkv_ref[:, :, 1]).abs().max().item()}")
  645. print(f"dV max diff: {(dqkv[:, :, 2] - dqkv_ref[:, :, 2]).abs().max().item()}")
  646. print(f"dQKV mean diff: {(dqkv - dqkv_ref).abs().mean().item()}")
  647. print(f"dQ Pytorch max diff: {(dqkv_pt[:, :, 0] - dqkv_ref[:, :, 0]).abs().max().item()}")
  648. print(f"dK Pytorch max diff: {(dqkv_pt[:, :, 1] - dqkv_ref[:, :, 1]).abs().max().item()}")
  649. print(f"dV Pytorch max diff: {(dqkv_pt[:, :, 2] - dqkv_ref[:, :, 2]).abs().max().item()}")
  650. print(f"dQKV Pytorch mean diff: {(dqkv_pt - dqkv_ref).abs().mean().item()}")
  651. # Check that FlashAttention's numerical error is at most twice the numerical error
  652. # of a Pytorch implementation.
  653. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item()
  654. if dropout_p > 0.0:
  655. assert (attn - attn_ref).abs().max().item() <= 2 * (attn_pt - attn_ref).abs().max().item()
  656. assert abs(dropout_fraction - dropout_p) <= 0.01
  657. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  658. assert (dqkv - dqkv_ref).abs().max().item() <= 2 * (dqkv_pt - dqkv_ref).abs().max().item()
  659. @pytest.mark.parametrize("kvpacked", [True, False])
  660. # @pytest.mark.parametrize("kvpacked", [False])
  661. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  662. # @pytest.mark.parametrize("dtype", [torch.bfloat16])
  663. @pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"])
  664. # @pytest.mark.parametrize("mha_type", ["mha"])
  665. @pytest.mark.parametrize("causal", [False, True])
  666. # @pytest.mark.parametrize("causal", [True])
  667. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  668. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192, 224, 256])
  669. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192])
  670. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192])
  671. # @pytest.mark.parametrize('d', [56, 80])
  672. # @pytest.mark.parametrize("d", [64])
  673. @pytest.mark.parametrize(
  674. "seqlen_q,seqlen_k",
  675. [
  676. (113, 203),
  677. (128, 217),
  678. (113, 211),
  679. (108, 256),
  680. (256, 512),
  681. (512, 256),
  682. (1024, 1024),
  683. (1023, 1024),
  684. (1024, 1023),
  685. (2048, 2048),
  686. ],
  687. )
  688. # @pytest.mark.parametrize('seqlen_q,seqlen_k', [(256, 128)])
  689. @pytest.mark.parametrize("dropout_p", [0.0, 0.17])
  690. # @pytest.mark.parametrize("dropout_p", [0.17])
  691. def test_flash_attn_output(seqlen_q, seqlen_k, d, dropout_p, causal, mha_type, dtype, kvpacked):
  692. if (
  693. max(seqlen_q, seqlen_k) >= 2048
  694. and torch.cuda.get_device_properties("cuda").total_memory <= 16 * 2**30
  695. ):
  696. pytest.skip() # Reference implementation OOM
  697. device = "cuda"
  698. # set seed
  699. torch.random.manual_seed(0)
  700. batch_size = 16
  701. nheads = 9
  702. nheads_k = nheads if mha_type == "mha" else (1 if mha_type == "mqa" else 3)
  703. assert nheads % nheads_k == 0
  704. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype, requires_grad=True)
  705. if kvpacked:
  706. kv = torch.randn(
  707. batch_size, seqlen_k, 2, nheads_k, d, device=device, dtype=dtype, requires_grad=True
  708. )
  709. else:
  710. k = torch.randn(
  711. batch_size, seqlen_k, nheads_k, d, device=device, dtype=dtype, requires_grad=True
  712. )
  713. v = torch.randn(
  714. batch_size, seqlen_k, nheads_k, d, device=device, dtype=dtype, requires_grad=True
  715. )
  716. if kvpacked:
  717. out, lse, S_dmask = flash_attn_kvpacked_func(
  718. q, kv, dropout_p, return_attn_probs=True, causal=causal
  719. )
  720. else:
  721. out, lse, S_dmask = flash_attn_func(
  722. q, k, v, dropout_p, return_attn_probs=True, causal=causal
  723. )
  724. if dropout_p > 0.0:
  725. S_dmask_converted = convert_flash_attn_S_to_softmax(
  726. S_dmask, seqlen_q, seqlen_k, None, None, d, dropout_p > 0.0, causal=causal
  727. )
  728. dropout_mask = S_dmask_converted >= 0
  729. attn_unnorm = S_dmask_converted.abs()
  730. if kvpacked:
  731. kv_rep = repeat(kv, "b s two h d -> b s two (h g) d", g=nheads // nheads_k)
  732. k_rep, v_rep = kv_rep.unbind(dim=2)
  733. else:
  734. k_rep = repeat(k, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  735. v_rep = repeat(v, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  736. attn = normalize_flash_attn_S(
  737. attn_unnorm, q, k_rep, v_rep, None, None, dropout_p > 0.0, causal=causal
  738. )
  739. dropout_fraction = get_dropout_fraction(dropout_mask, None, None, causal=causal).item()
  740. print(f"Actual dropout fraction: {dropout_fraction}")
  741. else:
  742. dropout_mask = None
  743. if kvpacked:
  744. out_ref, attn_ref = attention_kvpacked_ref(
  745. q, kv, None, None, dropout_p, dropout_mask, causal=causal
  746. )
  747. out_pt, attn_pt = attention_kvpacked_ref(
  748. q,
  749. kv,
  750. None,
  751. None,
  752. dropout_p,
  753. dropout_mask,
  754. causal=causal,
  755. upcast=False,
  756. reorder_ops=True,
  757. )
  758. else:
  759. out_ref, attn_ref = attention_ref(
  760. q, k, v, None, None, dropout_p, dropout_mask, causal=causal
  761. )
  762. out_pt, attn_pt = attention_ref(
  763. q,
  764. k,
  765. v,
  766. None,
  767. None,
  768. dropout_p,
  769. dropout_mask,
  770. causal=causal,
  771. upcast=False,
  772. reorder_ops=True,
  773. )
  774. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  775. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  776. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  777. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  778. if dropout_p > 0.0:
  779. print(f"Attention max diff: {(attn - attn_ref).abs().max().item()}")
  780. print(f"Attention Pytorch max diff: {(attn_pt - attn_ref).abs().max().item()}")
  781. g = torch.randn_like(out)
  782. do_o = (g.float() * out.float()).sum(-1)
  783. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  784. if kvpacked:
  785. (
  786. dq,
  787. dkv,
  788. ) = torch.autograd.grad(out, (q, kv), g)
  789. dk, dv = dkv.unbind(2)
  790. (
  791. dq_ref,
  792. dkv_ref,
  793. ) = torch.autograd.grad(out_ref, (q, kv), g)
  794. dk_ref, dv_ref = dkv_ref.unbind(2)
  795. (
  796. dq_pt,
  797. dkv_pt,
  798. ) = torch.autograd.grad(out_pt, (q, kv), g)
  799. dk_pt, dv_pt = dkv_pt.unbind(2)
  800. else:
  801. (
  802. dq,
  803. dk,
  804. dv,
  805. ) = torch.autograd.grad(out, (q, k, v), g)
  806. (
  807. dq_ref,
  808. dk_ref,
  809. dv_ref,
  810. ) = torch.autograd.grad(out_ref, (q, k, v), g)
  811. (
  812. dq_pt,
  813. dk_pt,
  814. dv_pt,
  815. ) = torch.autograd.grad(out_pt, (q, k, v), g)
  816. print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}")
  817. print(f"dK max diff: {(dk - dk_ref).abs().max().item()}")
  818. print(f"dV max diff: {(dv - dv_ref).abs().max().item()}")
  819. print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}")
  820. print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}")
  821. print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}")
  822. print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}")
  823. print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}")
  824. print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}")
  825. print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}")
  826. print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}")
  827. print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}")
  828. # Check that FlashAttention's numerical error is at most twice the numerical error
  829. # of a Pytorch implementation.
  830. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item()
  831. if dropout_p > 0.0:
  832. assert (attn - attn_ref).abs().max().item() <= 2 * (attn_pt - attn_ref).abs().max().item()
  833. assert abs(dropout_fraction - dropout_p) <= 0.01
  834. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  835. assert (dq - dq_ref).abs().max().item() <= 2 * (dq_pt - dq_ref).abs().max().item()
  836. assert (dk - dk_ref).abs().max().item() <= 2 * (dk_pt - dk_ref).abs().max().item()
  837. assert (dv - dv_ref).abs().max().item() <= 2 * (dv_pt - dv_ref).abs().max().item()
  838. @pytest.mark.parametrize("kvpacked", [True, False])
  839. # @pytest.mark.parametrize('kvpacked', [False])
  840. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  841. # @pytest.mark.parametrize('dtype', [torch.float16])
  842. @pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"])
  843. # @pytest.mark.parametrize('mha_type', ["mqa"])
  844. @pytest.mark.parametrize("causal", [False, True])
  845. # @pytest.mark.parametrize('causal', [True])
  846. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  847. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192, 224, 256])
  848. # @pytest.mark.parametrize('d', [64])
  849. @pytest.mark.parametrize(
  850. "seqlen_q,seqlen_k",
  851. [
  852. (113, 203),
  853. (128, 217),
  854. (113, 211),
  855. (108, 256),
  856. (256, 512),
  857. (512, 256),
  858. (1024, 1024),
  859. (1023, 1024),
  860. (1024, 1023),
  861. (2048, 2048),
  862. ],
  863. )
  864. # @pytest.mark.parametrize('seqlen_q,seqlen_k', [(128, 128)])
  865. @pytest.mark.parametrize("dropout_p", [0.0, 0.17])
  866. # @pytest.mark.parametrize('dropout_p', [0.0])
  867. def test_flash_attn_varlen_output(
  868. seqlen_q, seqlen_k, d, dropout_p, causal, mha_type, dtype, kvpacked
  869. ):
  870. if (
  871. max(seqlen_q, seqlen_k) >= 2048
  872. and torch.cuda.get_device_properties("cuda").total_memory <= 16 * 2**30
  873. ):
  874. pytest.skip() # Reference implementation OOM
  875. device = "cuda"
  876. # set seed
  877. torch.random.manual_seed(0)
  878. batch_size = 16
  879. nheads = 9
  880. nheads_k = nheads if mha_type == "mha" else (1 if mha_type == "mqa" else 3)
  881. assert nheads % nheads_k == 0
  882. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype, requires_grad=True)
  883. if kvpacked:
  884. kv = torch.randn(
  885. batch_size, seqlen_k, 2, nheads_k, d, device=device, dtype=dtype, requires_grad=True
  886. )
  887. else:
  888. k = torch.randn(
  889. batch_size, seqlen_k, nheads_k, d, device=device, dtype=dtype, requires_grad=True
  890. )
  891. v = torch.randn(
  892. batch_size, seqlen_k, nheads_k, d, device=device, dtype=dtype, requires_grad=True
  893. )
  894. query_padding_mask = generate_random_padding_mask(seqlen_q, batch_size, device, mode="random")
  895. key_padding_mask = generate_random_padding_mask(seqlen_k, batch_size, device, mode="random")
  896. # key_padding_mask = generate_random_padding_mask(seqlen_k, batch_size, device, mode='full')
  897. if kvpacked:
  898. (
  899. q_unpad,
  900. kv_unpad,
  901. cu_seqlens_q,
  902. cu_seqlens_k,
  903. max_seqlen_q,
  904. max_seqlen_k,
  905. q,
  906. kv,
  907. output_pad_fn,
  908. dq_pad_fn,
  909. dkv_pad_fn,
  910. ) = generate_qkv(q, *kv.unbind(dim=2), query_padding_mask, key_padding_mask, kvpacked=True)
  911. out_unpad, sm_lse, S_dmask = flash_attn_varlen_kvpacked_func(
  912. q_unpad,
  913. kv_unpad,
  914. cu_seqlens_q,
  915. cu_seqlens_k,
  916. max_seqlen_q,
  917. max_seqlen_k,
  918. dropout_p,
  919. return_attn_probs=True,
  920. causal=causal,
  921. )
  922. else:
  923. (
  924. q_unpad,
  925. k_unpad,
  926. v_unpad,
  927. cu_seqlens_q,
  928. cu_seqlens_k,
  929. max_seqlen_q,
  930. max_seqlen_k,
  931. q,
  932. k,
  933. v,
  934. output_pad_fn,
  935. dq_pad_fn,
  936. dk_pad_fn,
  937. ) = generate_qkv(q, k, v, query_padding_mask, key_padding_mask, kvpacked=False)
  938. out_unpad, sm_lse, S_dmask = flash_attn_varlen_func(
  939. q_unpad,
  940. k_unpad,
  941. v_unpad,
  942. cu_seqlens_q,
  943. cu_seqlens_k,
  944. max_seqlen_q,
  945. max_seqlen_k,
  946. dropout_p,
  947. return_attn_probs=True,
  948. causal=causal,
  949. )
  950. out = output_pad_fn(out_unpad)
  951. if dropout_p > 0.0:
  952. S_dmask_converted = convert_flash_attn_S_to_softmax(
  953. S_dmask,
  954. seqlen_q,
  955. seqlen_k,
  956. query_padding_mask,
  957. key_padding_mask,
  958. d,
  959. dropout_p > 0.0,
  960. causal=causal,
  961. )
  962. dropout_mask = S_dmask_converted >= 0
  963. attn_unnorm = S_dmask_converted.abs()
  964. if kvpacked:
  965. kv_rep = repeat(kv, "b s two h d -> b s two (h g) d", g=nheads // nheads_k)
  966. k_rep, v_rep = kv_rep.unbind(dim=2)
  967. else:
  968. k_rep = repeat(k, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  969. v_rep = repeat(v, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  970. attn = normalize_flash_attn_S(
  971. attn_unnorm,
  972. q,
  973. k_rep,
  974. v_rep,
  975. query_padding_mask,
  976. key_padding_mask,
  977. dropout_p > 0.0,
  978. causal=causal,
  979. )
  980. dropout_fraction = get_dropout_fraction(
  981. dropout_mask, query_padding_mask, key_padding_mask, causal=causal
  982. ).item()
  983. print(f"Actual dropout fraction: {dropout_fraction}")
  984. else:
  985. dropout_mask = None
  986. if kvpacked:
  987. out_ref, attn_ref = attention_kvpacked_ref(
  988. q, kv, query_padding_mask, key_padding_mask, dropout_p, dropout_mask, causal=causal
  989. )
  990. out_pt, attn_pt = attention_kvpacked_ref(
  991. q,
  992. kv,
  993. query_padding_mask,
  994. key_padding_mask,
  995. dropout_p,
  996. dropout_mask,
  997. causal=causal,
  998. upcast=False,
  999. reorder_ops=True,
  1000. )
  1001. else:
  1002. out_ref, attn_ref = attention_ref(
  1003. q, k, v, query_padding_mask, key_padding_mask, dropout_p, dropout_mask, causal=causal
  1004. )
  1005. out_pt, attn_pt = attention_ref(
  1006. q,
  1007. k,
  1008. v,
  1009. query_padding_mask,
  1010. key_padding_mask,
  1011. dropout_p,
  1012. dropout_mask,
  1013. causal=causal,
  1014. upcast=False,
  1015. reorder_ops=True,
  1016. )
  1017. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  1018. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  1019. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  1020. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  1021. if dropout_p > 0.0:
  1022. print(f"Attention max diff: {(attn - attn_ref).abs().max().item()}")
  1023. print(f"Attention Pytorch max diff: {(attn_pt - attn_ref).abs().max().item()}")
  1024. g = torch.randn_like(out)
  1025. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1026. if kvpacked:
  1027. (
  1028. dq_unpad,
  1029. dkv_unpad,
  1030. ) = torch.autograd.grad(out, (q_unpad, kv_unpad), g)
  1031. dk, dv = dkv_pad_fn(dkv_unpad).unbind(2)
  1032. (
  1033. dq_ref,
  1034. dkv_ref,
  1035. ) = torch.autograd.grad(out_ref, (q, kv), g)
  1036. dk_ref, dv_ref = dkv_ref.unbind(2)
  1037. (
  1038. dq_pt,
  1039. dkv_pt,
  1040. ) = torch.autograd.grad(out_pt, (q, kv), g)
  1041. dk_pt, dv_pt = dkv_pt.unbind(2)
  1042. else:
  1043. (
  1044. dq_unpad,
  1045. dk_unpad,
  1046. dv_unpad,
  1047. ) = torch.autograd.grad(out, (q_unpad, k_unpad, v_unpad), g)
  1048. dk = dk_pad_fn(dk_unpad)
  1049. dv = dk_pad_fn(dv_unpad)
  1050. (
  1051. dq_ref,
  1052. dk_ref,
  1053. dv_ref,
  1054. ) = torch.autograd.grad(out_ref, (q, k, v), g)
  1055. (
  1056. dq_pt,
  1057. dk_pt,
  1058. dv_pt,
  1059. ) = torch.autograd.grad(out_pt, (q, k, v), g)
  1060. dq = dq_pad_fn(dq_unpad)
  1061. print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}")
  1062. print(f"dK max diff: {(dk - dk_ref).abs().max().item()}")
  1063. print(f"dV max diff: {(dv - dv_ref).abs().max().item()}")
  1064. print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}")
  1065. print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}")
  1066. print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}")
  1067. print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}")
  1068. print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}")
  1069. print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}")
  1070. print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}")
  1071. print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}")
  1072. print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}")
  1073. # Check that FlashAttention's numerical error is at most twice the numerical error
  1074. # of a Pytorch implementation.
  1075. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item()
  1076. if dropout_p > 0.0:
  1077. assert (attn - attn_ref).abs().max().item() <= 2 * (attn_pt - attn_ref).abs().max().item()
  1078. assert abs(dropout_fraction - dropout_p) <= 0.01
  1079. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1080. assert (dq - dq_ref).abs().max().item() <= 2 * (dq_pt - dq_ref).abs().max().item()
  1081. assert (dk - dk_ref).abs().max().item() <= 2 * (dk_pt - dk_ref).abs().max().item()
  1082. assert (dv - dv_ref).abs().max().item() <= 2 * (dv_pt - dv_ref).abs().max().item()
  1083. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  1084. # @pytest.mark.parametrize("dtype", [torch.bfloat16])
  1085. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  1086. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192, 224, 256])
  1087. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192])
  1088. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192])
  1089. # @pytest.mark.parametrize('d', [56, 80])
  1090. # @pytest.mark.parametrize("d", [64, 128])
  1091. @pytest.mark.parametrize("swap_sq_sk", [False, True])
  1092. # @pytest.mark.parametrize("swap_sq_sk", [True])
  1093. @pytest.mark.parametrize(
  1094. "seqlen_q,seqlen_k",
  1095. [
  1096. (1, 239),
  1097. (3, 799),
  1098. (127, 512),
  1099. (127, 513),
  1100. (113, 203),
  1101. (128, 217),
  1102. (113, 211),
  1103. (108, 256),
  1104. (256, 512),
  1105. (1023, 1024),
  1106. ],
  1107. )
  1108. # @pytest.mark.parametrize('seqlen_q,seqlen_k', [(256, 128)])
  1109. def test_flash_attn_causal(seqlen_q, seqlen_k, swap_sq_sk, d, dtype):
  1110. if (
  1111. max(seqlen_q, seqlen_k) >= 2048
  1112. and torch.cuda.get_device_properties("cuda").total_memory <= 16 * 2**30
  1113. ):
  1114. pytest.skip() # Reference implementation OOM
  1115. if swap_sq_sk:
  1116. seqlen_q, seqlen_k = seqlen_k, seqlen_q
  1117. device = "cuda"
  1118. causal = True
  1119. # set seed
  1120. torch.random.manual_seed(0)
  1121. batch_size = 16
  1122. nheads = 9
  1123. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1124. k = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1125. v = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1126. out = flash_attn_func(q, k, v, 0.0, causal=causal)
  1127. out_ref, attn_ref = attention_ref(q, k, v, None, None, 0.0, None, causal=causal)
  1128. out_pt, attn_pt = attention_ref(
  1129. q,
  1130. k,
  1131. v,
  1132. None,
  1133. None,
  1134. 0.0,
  1135. None,
  1136. causal=causal,
  1137. upcast=False,
  1138. reorder_ops=True,
  1139. )
  1140. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  1141. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  1142. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  1143. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  1144. g = torch.randn_like(out)
  1145. do_o = (g.float() * out.float()).sum(-1)
  1146. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1147. (
  1148. dq,
  1149. dk,
  1150. dv,
  1151. ) = torch.autograd.grad(out, (q, k, v), g)
  1152. (
  1153. dq_ref,
  1154. dk_ref,
  1155. dv_ref,
  1156. ) = torch.autograd.grad(out_ref, (q, k, v), g)
  1157. (
  1158. dq_pt,
  1159. dk_pt,
  1160. dv_pt,
  1161. ) = torch.autograd.grad(out_pt, (q, k, v), g)
  1162. print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}")
  1163. print(f"dK max diff: {(dk - dk_ref).abs().max().item()}")
  1164. print(f"dV max diff: {(dv - dv_ref).abs().max().item()}")
  1165. print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}")
  1166. print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}")
  1167. print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}")
  1168. print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}")
  1169. print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}")
  1170. print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}")
  1171. print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}")
  1172. print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}")
  1173. print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}")
  1174. # Check that FlashAttention's numerical error is at most twice the numerical error
  1175. # of a Pytorch implementation.
  1176. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item() + 1e-5
  1177. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1178. assert (dq - dq_ref).abs().max().item() <= 2 * (dq_pt - dq_ref).abs().max().item() + 1e-5
  1179. assert (dk - dk_ref).abs().max().item() <= 2 * (dk_pt - dk_ref).abs().max().item() + 1e-5
  1180. assert (dv - dv_ref).abs().max().item() <= 2 * (dv_pt - dv_ref).abs().max().item() + 1e-5
  1181. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  1182. # @pytest.mark.parametrize("dtype", [torch.bfloat16])
  1183. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  1184. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192, 224, 256])
  1185. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192])
  1186. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192])
  1187. # @pytest.mark.parametrize('d', [56, 80])
  1188. # @pytest.mark.parametrize("d", [128])
  1189. @pytest.mark.parametrize("swap_sq_sk", [False, True])
  1190. # @pytest.mark.parametrize("swap_sq_sk", [True])
  1191. @pytest.mark.parametrize(
  1192. "seqlen_q,seqlen_k",
  1193. [
  1194. (1, 239),
  1195. (3, 799),
  1196. (127, 512),
  1197. (127, 513),
  1198. (113, 203),
  1199. (128, 217),
  1200. (113, 211),
  1201. (108, 256),
  1202. (256, 512),
  1203. (1023, 1024),
  1204. ],
  1205. )
  1206. # @pytest.mark.parametrize("seqlen_q,seqlen_k", [(256, 128)])
  1207. def test_flash_attn_varlen_causal(seqlen_q, seqlen_k, swap_sq_sk, d, dtype):
  1208. if (
  1209. max(seqlen_q, seqlen_k) >= 2048
  1210. and torch.cuda.get_device_properties("cuda").total_memory <= 16 * 2**30
  1211. ):
  1212. pytest.skip() # Reference implementation OOM
  1213. if swap_sq_sk:
  1214. seqlen_q, seqlen_k = seqlen_k, seqlen_q
  1215. device = "cuda"
  1216. causal = True
  1217. # set seed
  1218. torch.random.manual_seed(0)
  1219. batch_size = 16
  1220. nheads = 9
  1221. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1222. k = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1223. v = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1224. query_padding_mask = generate_random_padding_mask(seqlen_q, batch_size, device, mode="random")
  1225. key_padding_mask = generate_random_padding_mask(seqlen_k, batch_size, device, mode="random")
  1226. (
  1227. q_unpad,
  1228. k_unpad,
  1229. v_unpad,
  1230. cu_seqlens_q,
  1231. cu_seqlens_k,
  1232. max_seqlen_q,
  1233. max_seqlen_k,
  1234. q,
  1235. k,
  1236. v,
  1237. output_pad_fn,
  1238. dq_pad_fn,
  1239. dk_pad_fn,
  1240. ) = generate_qkv(q, k, v, query_padding_mask, key_padding_mask, kvpacked=False)
  1241. out_unpad = flash_attn_varlen_func(
  1242. q_unpad,
  1243. k_unpad,
  1244. v_unpad,
  1245. cu_seqlens_q,
  1246. cu_seqlens_k,
  1247. max_seqlen_q,
  1248. max_seqlen_k,
  1249. 0.0,
  1250. causal=causal,
  1251. )
  1252. out = output_pad_fn(out_unpad)
  1253. out_ref, attn_ref = attention_ref(
  1254. q, k, v, query_padding_mask, key_padding_mask, 0.0, None, causal=causal
  1255. )
  1256. out_pt, attn_pt = attention_ref(
  1257. q,
  1258. k,
  1259. v,
  1260. query_padding_mask,
  1261. key_padding_mask,
  1262. 0.0,
  1263. None,
  1264. causal=causal,
  1265. upcast=False,
  1266. reorder_ops=True,
  1267. )
  1268. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  1269. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  1270. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  1271. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  1272. g = torch.randn_like(out)
  1273. do_o = (g.float() * out.float()).sum(-1)
  1274. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1275. (
  1276. dq_unpad,
  1277. dk_unpad,
  1278. dv_unpad,
  1279. ) = torch.autograd.grad(out, (q_unpad, k_unpad, v_unpad), g)
  1280. dq = dq_pad_fn(dq_unpad)
  1281. dk = dk_pad_fn(dk_unpad)
  1282. dv = dk_pad_fn(dv_unpad)
  1283. (
  1284. dq_ref,
  1285. dk_ref,
  1286. dv_ref,
  1287. ) = torch.autograd.grad(out_ref, (q, k, v), g)
  1288. (
  1289. dq_pt,
  1290. dk_pt,
  1291. dv_pt,
  1292. ) = torch.autograd.grad(out_pt, (q, k, v), g)
  1293. print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}")
  1294. print(f"dK max diff: {(dk - dk_ref).abs().max().item()}")
  1295. print(f"dV max diff: {(dv - dv_ref).abs().max().item()}")
  1296. print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}")
  1297. print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}")
  1298. print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}")
  1299. print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}")
  1300. print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}")
  1301. print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}")
  1302. print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}")
  1303. print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}")
  1304. print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}")
  1305. # Check that FlashAttention's numerical error is at most twice the numerical error
  1306. # of a Pytorch implementation.
  1307. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item() + 1e-5
  1308. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1309. assert (dq - dq_ref).abs().max().item() <= 2 * (dq_pt - dq_ref).abs().max().item() + 1e-5
  1310. assert (dk - dk_ref).abs().max().item() <= 2 * (dk_pt - dk_ref).abs().max().item() + 1e-5
  1311. assert (dv - dv_ref).abs().max().item() <= 2 * (dv_pt - dv_ref).abs().max().item() + 1e-5
  1312. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  1313. # @pytest.mark.parametrize("dtype", [torch.float16])
  1314. @pytest.mark.parametrize("causal", [False, True])
  1315. # @pytest.mark.parametrize("causal", [True])
  1316. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  1317. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192, 224, 256])
  1318. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192])
  1319. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192])
  1320. # @pytest.mark.parametrize('d', [56, 80])
  1321. # @pytest.mark.parametrize("d", [64])
  1322. @pytest.mark.parametrize("swap_sq_sk", [False, True])
  1323. # @pytest.mark.parametrize("swap_sq_sk", [False])
  1324. @pytest.mark.parametrize(
  1325. "seqlen_q,seqlen_k",
  1326. [
  1327. (3, 1024),
  1328. (1, 339),
  1329. (64, 800),
  1330. (3, 799),
  1331. (64, 2048),
  1332. (16, 20000),
  1333. (16, 100000),
  1334. (128, 128),
  1335. (256, 256),
  1336. ],
  1337. )
  1338. # @pytest.mark.parametrize('seqlen_q,seqlen_k', [(256, 128)])
  1339. def test_flash_attn_splitkv(seqlen_q, seqlen_k, swap_sq_sk, d, causal, dtype):
  1340. if swap_sq_sk:
  1341. seqlen_q, seqlen_k = seqlen_k, seqlen_q
  1342. device = "cuda"
  1343. # set seed
  1344. torch.random.manual_seed(0)
  1345. batch_size = 1
  1346. nheads = 12
  1347. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1348. k = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1349. v = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1350. out, lse, _ = flash_attn_func(q, k, v, 0.0, causal=causal, return_attn_probs=True)
  1351. out_ref, attn_ref = attention_ref(q, k, v, None, None, 0.0, None, causal=causal)
  1352. out_pt, attn_pt = attention_ref(
  1353. q,
  1354. k,
  1355. v,
  1356. None,
  1357. None,
  1358. 0.0,
  1359. None,
  1360. causal=causal,
  1361. upcast=False,
  1362. reorder_ops=True,
  1363. )
  1364. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  1365. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  1366. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  1367. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  1368. g = torch.randn_like(out)
  1369. do_o = (g.float() * out.float()).sum(-1)
  1370. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1371. (
  1372. dq,
  1373. dk,
  1374. dv,
  1375. ) = torch.autograd.grad(out, (q, k, v), g)
  1376. (
  1377. dq_ref,
  1378. dk_ref,
  1379. dv_ref,
  1380. ) = torch.autograd.grad(out_ref, (q, k, v), g)
  1381. (
  1382. dq_pt,
  1383. dk_pt,
  1384. dv_pt,
  1385. ) = torch.autograd.grad(out_pt, (q, k, v), g)
  1386. print(f"dQ max diff: {(dq - dq_ref).abs().max().item()}")
  1387. print(f"dK max diff: {(dk - dk_ref).abs().max().item()}")
  1388. print(f"dV max diff: {(dv - dv_ref).abs().max().item()}")
  1389. print(f"dQ mean diff: {(dq - dq_ref).abs().mean().item()}")
  1390. print(f"dK mean diff: {(dk - dk_ref).abs().mean().item()}")
  1391. print(f"dV mean diff: {(dv - dv_ref).abs().mean().item()}")
  1392. print(f"dQ Pytorch max diff: {(dq_pt - dq_ref).abs().max().item()}")
  1393. print(f"dK Pytorch max diff: {(dk_pt - dk_ref).abs().max().item()}")
  1394. print(f"dV Pytorch max diff: {(dv_pt - dv_ref).abs().max().item()}")
  1395. print(f"dQ Pytorch mean diff: {(dq_pt - dq_ref).abs().mean().item()}")
  1396. print(f"dK Pytorch mean diff: {(dk_pt - dk_ref).abs().mean().item()}")
  1397. print(f"dV Pytorch mean diff: {(dv_pt - dv_ref).abs().mean().item()}")
  1398. # Check that FlashAttention's numerical error is at most twice the numerical error
  1399. # of a Pytorch implementation.
  1400. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item() + 1e-5
  1401. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1402. assert (dq - dq_ref).abs().max().item() <= 2 * (dq_pt - dq_ref).abs().max().item() + 2e-4
  1403. assert (dk - dk_ref).abs().max().item() <= 2 * (dk_pt - dk_ref).abs().max().item() + 2e-4
  1404. assert (dv - dv_ref).abs().max().item() <= 2 * (dv_pt - dv_ref).abs().max().item() + 2e-4
  1405. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  1406. # @pytest.mark.parametrize("dtype", [torch.float16])
  1407. @pytest.mark.parametrize("num_splits", [1, 0])
  1408. # @pytest.mark.parametrize("num_splits", [0])
  1409. @pytest.mark.parametrize("mha_type", ["mha", "mqa", "gqa"])
  1410. # @pytest.mark.parametrize("mha_type", ["mha"])
  1411. @pytest.mark.parametrize("new_kv", [False, True])
  1412. # @pytest.mark.parametrize("new_kv", [True])
  1413. @pytest.mark.parametrize("causal", [False, True])
  1414. # @pytest.mark.parametrize("causal", [True])
  1415. @pytest.mark.parametrize("seqlen_new_eq_seqlen_q", [True, False])
  1416. # @pytest.mark.parametrize("seqlen_new_eq_seqlen_q", [True])
  1417. @pytest.mark.parametrize("rotary_interleaved", [False, True])
  1418. # @pytest.mark.parametrize("rotary_interleaved", [False])
  1419. @pytest.mark.parametrize("rotary_fraction", [0.0, 0.5, 1.0])
  1420. # @pytest.mark.parametrize("rotary_fraction", [1.0])
  1421. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  1422. # @pytest.mark.parametrize('d', [32, 64, 96, 128, 160, 192, 224, 256])
  1423. # @pytest.mark.parametrize('d', [32, 40, 64, 80, 96, 128, 160, 192])
  1424. # @pytest.mark.parametrize('d', [56, 80])
  1425. # @pytest.mark.parametrize("d", [64])
  1426. @pytest.mark.parametrize(
  1427. "seqlen_q,seqlen_k",
  1428. [
  1429. (1, 128),
  1430. (1, 339),
  1431. (3, 1024),
  1432. (64, 800),
  1433. (64, 256),
  1434. (3, 799),
  1435. (64, 2048),
  1436. (16, 20000),
  1437. (1, 128 * 1024),
  1438. (16, 128 * 1024),
  1439. (128, 128),
  1440. ],
  1441. )
  1442. # @pytest.mark.parametrize('seqlen_q,seqlen_k', [(256, 128)])
  1443. def test_flash_attn_kvcache(
  1444. seqlen_q,
  1445. seqlen_k,
  1446. d,
  1447. rotary_fraction,
  1448. rotary_interleaved,
  1449. seqlen_new_eq_seqlen_q,
  1450. causal,
  1451. new_kv,
  1452. mha_type,
  1453. num_splits,
  1454. dtype,
  1455. ):
  1456. if seqlen_q > seqlen_k and new_kv:
  1457. pytest.skip()
  1458. if not new_kv and rotary_fraction > 0.0:
  1459. pytest.skip()
  1460. device = "cuda"
  1461. # set seed
  1462. torch.random.manual_seed(0)
  1463. batch_size = 2
  1464. nheads = 6
  1465. # rotary_dim must be a multiple of 16, and must be <= d
  1466. rotary_dim = math.floor(int(rotary_fraction * d) / 16) * 16
  1467. nheads_k = nheads if mha_type == "mha" else (1 if mha_type == "mqa" else 3)
  1468. assert nheads % nheads_k == 0
  1469. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype)
  1470. seqlen_new = seqlen_q if seqlen_new_eq_seqlen_q else torch.randint(1, seqlen_q + 1, (1,)).item()
  1471. if new_kv:
  1472. k = torch.randn(batch_size, seqlen_new, nheads_k, d, device=device, dtype=dtype)
  1473. v = torch.randn(batch_size, seqlen_new, nheads_k, d, device=device, dtype=dtype)
  1474. else:
  1475. k, v = None, None
  1476. k_cache = torch.randn(batch_size, seqlen_k, nheads_k, d, device=device, dtype=dtype)
  1477. v_cache = torch.randn(batch_size, seqlen_k, nheads_k, d, device=device, dtype=dtype)
  1478. cache_seqlens = torch.randint(
  1479. 0,
  1480. # If we don't use seqlen_q in the case of causal and rotary, cos/sin won't be long enough
  1481. (seqlen_k - (seqlen_q if causal and rotary_dim > 1 else seqlen_new) + 1)
  1482. if new_kv
  1483. else (seqlen_k + 1),
  1484. (batch_size,),
  1485. dtype=torch.int32,
  1486. device=device,
  1487. )
  1488. # cache_seqlens = torch.tensor([64], dtype=torch.int32, device=device)
  1489. if rotary_dim > 0:
  1490. angle = torch.rand(seqlen_k, rotary_dim // 2, device=device) * 2 * math.pi
  1491. cos = torch.cos(angle).to(dtype=dtype)
  1492. sin = torch.sin(angle).to(dtype=dtype)
  1493. if causal:
  1494. q_ro = apply_rotary_emb(
  1495. q, cos, sin, seqlen_offsets=cache_seqlens, interleaved=rotary_interleaved
  1496. )
  1497. else:
  1498. q_ro = rearrange(
  1499. apply_rotary_emb(
  1500. rearrange(q, "b s h d -> b 1 (s h) d"),
  1501. cos,
  1502. sin,
  1503. seqlen_offsets=cache_seqlens,
  1504. interleaved=rotary_interleaved,
  1505. ),
  1506. "b 1 (s h) d -> b s h d",
  1507. s=seqlen_q,
  1508. )
  1509. # q_ro = q
  1510. k_ro = apply_rotary_emb(
  1511. k, cos, sin, seqlen_offsets=cache_seqlens, interleaved=rotary_interleaved
  1512. )
  1513. else:
  1514. cos, sin = None, None
  1515. q_ro, k_ro = q, k
  1516. # k_cache[:, 64:] = -1
  1517. k_cache_ref = k_cache.clone()
  1518. v_cache_ref = v_cache.clone()
  1519. arange = rearrange(torch.arange(seqlen_k, device=device), "s -> 1 s")
  1520. cache_seqlens_expanded = rearrange(cache_seqlens, "b -> b 1")
  1521. if new_kv:
  1522. update_mask = torch.logical_and(
  1523. cache_seqlens_expanded <= arange, arange < cache_seqlens_expanded + seqlen_new
  1524. )
  1525. k_cache_ref[update_mask] = rearrange(k_ro, "b s ... -> (b s) ...")
  1526. v_cache_ref[update_mask] = rearrange(v, "b s ... -> (b s) ...")
  1527. k_cache_rep = repeat(k_cache_ref, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  1528. v_cache_rep = repeat(v_cache_ref, "b s h d -> b s (h g) d", g=nheads // nheads_k)
  1529. out = flash_attn_with_kvcache(
  1530. q,
  1531. k_cache,
  1532. v_cache,
  1533. k,
  1534. v,
  1535. cos,
  1536. sin,
  1537. cache_seqlens,
  1538. causal=causal,
  1539. rotary_interleaved=rotary_interleaved,
  1540. num_splits=num_splits,
  1541. )
  1542. # out = flash_attn_with_kvcache(q, k_cache, v_cache, cache_seqlens=cache_seqlens, causal=causal)
  1543. # out = flash_attn_with_kvcache(q, k_cache, v_cache, causal=causal)
  1544. # qk = torch.einsum("bqhd,bkhd->bhqk", q, k_cache_ref)
  1545. # m = qk.amax(-1, keepdim=True)
  1546. # s_tmp = torch.exp((qk - m) / math.sqrt(d))
  1547. # o1 = torch.einsum('bhst,bthd->bshd', s_tmp, v_cache_ref)
  1548. # lse_ref = torch.logsumexp(qk / math.sqrt(d), -1)
  1549. # probs = torch.softmax(qk, dim=-1)
  1550. key_padding_mask = arange < cache_seqlens_expanded + (seqlen_new if new_kv else 0)
  1551. out_ref, _ = attention_ref(
  1552. q_ro, k_cache_rep, v_cache_rep, None, key_padding_mask, 0.0, None, causal=causal
  1553. )
  1554. out_pt, _ = attention_ref(
  1555. q_ro,
  1556. k_cache_rep,
  1557. v_cache_rep,
  1558. None,
  1559. key_padding_mask,
  1560. 0.0,
  1561. None,
  1562. causal=causal,
  1563. upcast=False,
  1564. reorder_ops=True,
  1565. )
  1566. print(f"Output max diff: {(out - out_ref).abs().max().item()}")
  1567. print(f"Output mean diff: {(out - out_ref).abs().mean().item()}")
  1568. print(f"Pytorch max diff: {(out_pt - out_ref).abs().max().item()}")
  1569. print(f"Pytorch mean diff: {(out_pt - out_ref).abs().mean().item()}")
  1570. # Check that FlashAttention's numerical error is at most twice the numerical error
  1571. # of a Pytorch implementation.
  1572. if new_kv:
  1573. assert torch.allclose(k_cache, k_cache_ref, rtol=1e-3, atol=1e-3)
  1574. assert torch.equal(v_cache, v_cache_ref)
  1575. assert (out - out_ref).abs().max().item() <= 3 * (out_pt - out_ref).abs().max().item() + 1e-5
  1576. # @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  1577. @pytest.mark.parametrize("dtype", [torch.float16])
  1578. @pytest.mark.parametrize("causal", [False, True])
  1579. # @pytest.mark.parametrize('causal', [True])
  1580. @pytest.mark.parametrize("d", [32, 40, 59, 64, 80, 96, 111, 128, 160, 192, 224, 256])
  1581. # @pytest.mark.parametrize('d', [32, 56, 64, 80, 96, 128])
  1582. # @pytest.mark.parametrize("d", [32, 64, 96, 128, 160, 192])
  1583. # @pytest.mark.parametrize('d', [128])
  1584. @pytest.mark.parametrize(
  1585. "seqlen_q,seqlen_k",
  1586. [
  1587. (1, 239),
  1588. (239, 1),
  1589. (3, 799),
  1590. (799, 3),
  1591. (1024, 128),
  1592. (97, 97),
  1593. (128, 128),
  1594. (200, 200),
  1595. (256, 256),
  1596. (257, 257),
  1597. (384, 384),
  1598. (512, 512),
  1599. (768, 768),
  1600. (1024, 1024),
  1601. ],
  1602. )
  1603. @pytest.mark.parametrize("dropout_p", [0.0, 0.17])
  1604. # @pytest.mark.parametrize("dropout_p", [0.0])
  1605. def test_flash_attn_race_condition(seqlen_q, seqlen_k, d, dropout_p, causal, dtype):
  1606. device = "cuda"
  1607. # set seed
  1608. torch.random.manual_seed(0)
  1609. batch_size = 60 # Sometimes we need large batch size for the race conditions to trigger
  1610. nheads = 4
  1611. q = torch.randn(batch_size, seqlen_q, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1612. k = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1613. v = torch.randn(batch_size, seqlen_k, nheads, d, device=device, dtype=dtype, requires_grad=True)
  1614. torch.random.manual_seed(42)
  1615. out0, lse0, _ = flash_attn_func(q, k, v, dropout_p, causal=causal, return_attn_probs=True)
  1616. g = torch.randn_like(out0)
  1617. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1618. (
  1619. dq0,
  1620. dk0,
  1621. dv0,
  1622. ) = torch.autograd.grad(out0, (q, k, v), g)
  1623. # Numerical error if we just do any arithmetic on dq
  1624. dq_atol = 2 * ((dq0 + 0.3 - 0.3) - dq0).abs().max().item()
  1625. for i in range(250):
  1626. torch.random.manual_seed(42)
  1627. out, lse, _ = flash_attn_func(q, k, v, dropout_p, causal=causal, return_attn_probs=True)
  1628. assert torch.equal(out, out0)
  1629. assert torch.equal(lse, lse0)
  1630. if d <= MAX_HEADDIM_SM8x or (is_sm80 or is_sm90):
  1631. (
  1632. dq,
  1633. dk,
  1634. dv,
  1635. ) = torch.autograd.grad(out, (q, k, v), g)
  1636. dq_equal = torch.allclose(dq, dq0, atol=dq_atol)
  1637. if not dq_equal:
  1638. print(f"Iter {i}, {dq_atol = }, dQ max diff: {(dq - dq0).abs().max().item()}")
  1639. assert torch.equal(dv, dv0)
  1640. assert torch.equal(dk, dk0)
  1641. assert dq_equal
  1642. @pytest.mark.parametrize("dtype", [torch.float16])
  1643. @pytest.mark.parametrize("causal", [False, True])
  1644. # @pytest.mark.parametrize('causal', [False])
  1645. @pytest.mark.parametrize("d", [16, 32, 64])
  1646. # @pytest.mark.parametrize('d', [16])
  1647. @pytest.mark.parametrize("seqlen", [1, 2, 5, 17, 128])
  1648. # @pytest.mark.parametrize('seqlen', [2])
  1649. def test_flash_attn_bwd_overflow(seqlen, d, causal, dtype):
  1650. """We previously had a bug where not masking elements beyond seqlen_k caused NaN in dQ,
  1651. in the case where seqlen % 128 != 0.
  1652. """
  1653. device = "cuda"
  1654. # set seed
  1655. torch.random.manual_seed(0)
  1656. batch_size = 2
  1657. nheads = 5
  1658. q = torch.randn([batch_size, seqlen, nheads, d], dtype=dtype, device="cuda") * 5
  1659. k, v = [
  1660. torch.randn([batch_size, seqlen, nheads, d], dtype=dtype, device="cuda") * 3
  1661. for _ in range(2)
  1662. ]
  1663. q.requires_grad_(True)
  1664. k.requires_grad_(True)
  1665. v.requires_grad_(True)
  1666. out = flash_attn_func(q, k, v, causal=causal)
  1667. g = torch.randn_like(out)
  1668. out.backward(g)
  1669. q_pt = q.detach().clone().requires_grad_(True)
  1670. k_pt = k.detach().clone().requires_grad_(True)
  1671. v_pt = v.detach().clone().requires_grad_(True)
  1672. out_pt, _ = attention_ref(q_pt, k_pt, v_pt, causal=causal, upcast=False, reorder_ops=True)
  1673. out_pt.backward(g)
  1674. q_ref = q.detach().clone().requires_grad_(True)
  1675. k_ref = k.detach().clone().requires_grad_(True)
  1676. v_ref = v.detach().clone().requires_grad_(True)
  1677. out_ref, attn_ref = attention_ref(q_ref, k_ref, v_ref, causal=causal)
  1678. out_ref.backward(g)
  1679. print(f"dQ max diff: {(q.grad - q_ref.grad).abs().max().item()}")
  1680. print(f"dK max diff: {(k.grad - k_ref.grad).abs().max().item()}")
  1681. print(f"dV max diff: {(v.grad - v_ref.grad).abs().max().item()}")
  1682. print(f"dQ Pytorch max diff: {(q_pt.grad - q_ref.grad).abs().max().item()}")
  1683. print(f"dK Pytorch max diff: {(k_pt.grad - k_ref.grad).abs().max().item()}")
  1684. print(f"dV Pytorch max diff: {(v_pt.grad - v_ref.grad).abs().max().item()}")
  1685. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item()
  1686. assert (q.grad - q_ref.grad).abs().max().item() <= 5 * (
  1687. q_pt.grad - q_ref.grad
  1688. ).abs().max().item() + 1e-3
  1689. assert (k.grad - k_ref.grad).abs().max().item() <= 5 * (
  1690. k_pt.grad - k_ref.grad
  1691. ).abs().max().item() + 1e-3
  1692. assert (v.grad - v_ref.grad).abs().max().item() <= 5 * (
  1693. v_pt.grad - v_ref.grad
  1694. ).abs().max().item() + 1e-3
  1695. @pytest.mark.parametrize("dtype", ([torch.float16] if is_sm75 else [torch.float16, torch.bfloat16]))
  1696. # @pytest.mark.parametrize('dtype', [torch.bfloat16])
  1697. @pytest.mark.parametrize("causal", [False, True])
  1698. # @pytest.mark.parametrize('causal', [False])
  1699. @pytest.mark.parametrize("d", [64, 128])
  1700. # @pytest.mark.parametrize('d', [64])
  1701. @pytest.mark.parametrize("seqlen", [97, 128, 200, 256])
  1702. # @pytest.mark.parametrize('seqlen', [128])
  1703. def test_flash_attn_bwd_transpose(seqlen, d, causal, dtype):
  1704. """We previously had a bug where we were using the wrong strides of dout, which shows up
  1705. when dout is not contiguous.
  1706. """
  1707. device = "cuda"
  1708. # set seed
  1709. torch.random.manual_seed(0)
  1710. batch_size = 5
  1711. nheads = 2
  1712. q, k, v = [
  1713. torch.randn([batch_size, seqlen, nheads, d], dtype=dtype, device="cuda", requires_grad=True)
  1714. for _ in range(3)
  1715. ]
  1716. out = rearrange(flash_attn_func(q, k, v, causal=causal), "b s ... -> s b ...")
  1717. # So g is not contiguous
  1718. g = torch.randn(seqlen, 2 * batch_size, nheads, d, dtype=dtype, device="cuda")[:, ::2]
  1719. out.backward(g)
  1720. q_pt = q.detach().clone().requires_grad_(True)
  1721. k_pt = k.detach().clone().requires_grad_(True)
  1722. v_pt = v.detach().clone().requires_grad_(True)
  1723. out_pt, attn_pt = attention_ref(q_pt, k_pt, v_pt, causal=causal, upcast=False, reorder_ops=True)
  1724. out_pt = rearrange(out_pt, "b s ... -> s b ...")
  1725. out_pt.backward(g)
  1726. q_ref = q.detach().clone().requires_grad_(True)
  1727. k_ref = k.detach().clone().requires_grad_(True)
  1728. v_ref = v.detach().clone().requires_grad_(True)
  1729. out_ref, attn_ref = attention_ref(q_ref, k_ref, v_ref, causal=causal)
  1730. out_ref = rearrange(out_ref, "b s ... -> s b ...")
  1731. out_ref.backward(g)
  1732. print(f"dQ max diff: {(q.grad - q_ref.grad).abs().max().item()}")
  1733. print(f"dK max diff: {(k.grad - k_ref.grad).abs().max().item()}")
  1734. print(f"dV max diff: {(v.grad - v_ref.grad).abs().max().item()}")
  1735. print(f"dQ Pytorch max diff: {(q_pt.grad - q_ref.grad).abs().max().item()}")
  1736. print(f"dK Pytorch max diff: {(k_pt.grad - k_ref.grad).abs().max().item()}")
  1737. print(f"dV Pytorch max diff: {(v_pt.grad - v_ref.grad).abs().max().item()}")
  1738. assert (out - out_ref).abs().max().item() <= 2 * (out_pt - out_ref).abs().max().item()
  1739. assert (q.grad - q_ref.grad).abs().max().item() <= 2 * (
  1740. q_pt.grad - q_ref.grad
  1741. ).abs().max().item()
  1742. assert (k.grad - k_ref.grad).abs().max().item() <= 2 * (
  1743. k_pt.grad - k_ref.grad
  1744. ).abs().max().item()
  1745. assert (v.grad - v_ref.grad).abs().max().item() <= 2 * (
  1746. v_pt.grad - v_ref.grad
  1747. ).abs().max().item()
  1748. @pytest.mark.parametrize("dtype", [torch.float16])
  1749. @pytest.mark.parametrize("causal", [False, True])
  1750. # @pytest.mark.parametrize('causal', [False])
  1751. @pytest.mark.parametrize("d", [16, 32, 64])
  1752. # @pytest.mark.parametrize('d', [16])
  1753. def test_flash_attn_bwd_varlen_overflow(d, causal, dtype):
  1754. """We previously had a bug where not masking elements beyond seqlen_k caused NaN in dQ,
  1755. in the case where seqlen % 128 != 0 or varlen.
  1756. """
  1757. device = "cuda"
  1758. # set seed
  1759. torch.random.manual_seed(0)
  1760. nheads = 5
  1761. q_cuseqlen = torch.tensor([0, 76, 110, 256], device=device, dtype=torch.int32)
  1762. k_cuseqlen = torch.tensor([0, 1, 2, 3], device=device, dtype=torch.int32)
  1763. Mq = 256
  1764. Mk = 3
  1765. q = torch.randn([Mq, nheads, d], dtype=dtype, device=device) * 3
  1766. k, v = [torch.randn([Mk, nheads, d], dtype=dtype, device=device) * 3 for _ in range(2)]
  1767. q.requires_grad_(True)
  1768. k.requires_grad_(True)
  1769. v.requires_grad_(True)
  1770. out = flash_attn_varlen_func(q, k, v, q_cuseqlen, k_cuseqlen, Mq, Mk, causal=causal)
  1771. g = torch.randn_like(out)
  1772. out.backward(g)
  1773. assert not q.grad.isnan().any()
  1774. assert not k.grad.isnan().any()
  1775. assert not v.grad.isnan().any()