triton_flash_attn.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. #!/usr/bin/env python
  2. """
  3. Fused Attention
  4. ===============
  5. This is a Triton implementation of the Flash Attention v2 algorithm from Tri Dao
  6. (https://tridao.me/publications/flash2/flash2.pdf)
  7. Credits: OpenAI kernel team, AMD ML Frameworks Triton team
  8. Features supported:
  9. 1) Fwd with causal masking
  10. 2) Any sequence lengths without padding (currently fwd kernel only)
  11. 3) Support for different sequence lengths for q and k
  12. 4) Nested tensor API currently does not support dropout or bias.
  13. Not currently supported:
  14. 1) Non power of two head dims
  15. """
  16. import torch
  17. import triton
  18. import triton.language as tl
  19. torch_dtype: tl.constexpr = torch.float16
  20. @triton.jit
  21. def cdiv_fn(x, y):
  22. return (x + y - 1) // y
  23. @triton.jit
  24. def max_fn(x, y):
  25. return tl.math.max(x, y)
  26. @triton.jit
  27. def dropout_offsets(philox_seed, philox_offset, dropout_p, m, n, stride):
  28. ms = tl.arange(0, m)
  29. ns = tl.arange(0, n)
  30. return philox_offset + ms[:, None] * stride + ns[None, :]
  31. @triton.jit
  32. def dropout_rng(philox_seed, philox_offset, dropout_p, m, n, stride):
  33. rng_offsets = dropout_offsets(philox_seed, philox_offset, dropout_p, m, n,
  34. stride).to(tl.uint32)
  35. # TODO: use tl.randint for better performance
  36. return tl.rand(philox_seed, rng_offsets)
  37. @triton.jit
  38. def dropout_mask(philox_seed, philox_offset, dropout_p, m, n, stride):
  39. rng_output = dropout_rng(philox_seed, philox_offset, dropout_p, m, n,
  40. stride)
  41. rng_keep = rng_output > dropout_p
  42. return rng_keep
  43. @triton.jit
  44. def load_fn(block_ptr, first, second, pad):
  45. if first and second:
  46. tensor = tl.load(block_ptr, boundary_check=(0, 1), padding_option=pad)
  47. elif first:
  48. tensor = tl.load(block_ptr, boundary_check=(0, ), padding_option=pad)
  49. elif second:
  50. tensor = tl.load(block_ptr, boundary_check=(1, ), padding_option=pad)
  51. else:
  52. tensor = tl.load(block_ptr)
  53. return tensor
  54. @triton.jit
  55. def _attn_fwd_inner(
  56. acc,
  57. l_i,
  58. m_i,
  59. q,
  60. K_block_ptr,
  61. V_block_ptr,
  62. start_m,
  63. actual_seqlen_k,
  64. dropout_p,
  65. philox_seed,
  66. batch_philox_offset,
  67. encoded_softmax_block_ptr,
  68. block_min,
  69. block_max,
  70. offs_n_causal,
  71. masked_blocks,
  72. n_extra_tokens,
  73. bias_ptr,
  74. IS_CAUSAL: tl.constexpr,
  75. BLOCK_M: tl.constexpr,
  76. BLOCK_DMODEL: tl.constexpr,
  77. BLOCK_N: tl.constexpr,
  78. OFFS_M: tl.constexpr,
  79. OFFS_N: tl.constexpr,
  80. PRE_LOAD_V: tl.constexpr,
  81. MASK_STEPS: tl.constexpr,
  82. ENABLE_DROPOUT: tl.constexpr,
  83. RETURN_ENCODED_SOFTMAX: tl.constexpr,
  84. PADDED_HEAD: tl.constexpr,
  85. ):
  86. # loop over k, v, and update accumulator
  87. for start_n in range(block_min, block_max, BLOCK_N):
  88. # For padded blocks, we will overrun the tensor size if
  89. # we load all BLOCK_N. For others, the blocks are all within range.
  90. k = load_fn(
  91. K_block_ptr,
  92. PADDED_HEAD,
  93. MASK_STEPS and (n_extra_tokens != 0),
  94. "zero",
  95. )
  96. if PRE_LOAD_V:
  97. v = load_fn(
  98. V_block_ptr,
  99. MASK_STEPS and (n_extra_tokens != 0),
  100. PADDED_HEAD,
  101. "zero",
  102. )
  103. qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
  104. # We start from end of seqlen_k so only the first iteration would need
  105. # to be checked for padding if it is not a multiple of block_n
  106. # TODO: This can be optimized to only be true for the padded block.
  107. if MASK_STEPS: # noqa: SIM102
  108. # If this is the last block / iteration, we want to
  109. # mask if the sequence length is not a multiple of block size
  110. # a solution is to always do BLOCK_M // BLOCK_N + 1 steps
  111. # if not is_modulo_mn. last step might get wasted but that is okay.
  112. # check if this masking works for that case.
  113. if (start_n + BLOCK_N == block_max) and (n_extra_tokens != 0):
  114. boundary_m = tl.full([BLOCK_M],
  115. actual_seqlen_k,
  116. dtype=tl.int32)
  117. size_n = start_n + OFFS_N[None, :]
  118. mask = size_n < boundary_m[:, None]
  119. qk = tl.where(mask, qk, float("-inf"))
  120. if IS_CAUSAL:
  121. causal_boundary = start_n + offs_n_causal
  122. causal_mask = OFFS_M[:, None] >= causal_boundary[None, :]
  123. qk = tl.where(causal_mask, qk, float("-inf"))
  124. # -- compute qk ----
  125. qk += tl.dot(q, k)
  126. if bias_ptr is not None:
  127. bias = load_fn(bias_ptr, False, MASK_STEPS
  128. and (n_extra_tokens != 0), "zero")
  129. # While bias is added after multiplying qk with sm_scale, our
  130. # optimization to use 2^x instead of e^x results in an additional
  131. # scale factor of log2(e) which we must also multiply the bias with.
  132. qk += bias * 1.44269504089
  133. m_ij = tl.maximum(m_i, tl.max(qk, 1))
  134. qk = qk - m_ij[:, None]
  135. p = tl.math.exp2(qk)
  136. # CAVEAT: Must update l_ij before applying dropout
  137. l_ij = tl.sum(p, 1)
  138. if ENABLE_DROPOUT:
  139. philox_offset = (batch_philox_offset +
  140. start_m * BLOCK_M * actual_seqlen_k + start_n -
  141. BLOCK_N)
  142. keep = dropout_mask(
  143. philox_seed,
  144. philox_offset,
  145. dropout_p,
  146. BLOCK_M,
  147. BLOCK_N,
  148. actual_seqlen_k,
  149. )
  150. if RETURN_ENCODED_SOFTMAX:
  151. tl.store(
  152. encoded_softmax_block_ptr,
  153. tl.where(keep, p,
  154. -p).to(encoded_softmax_block_ptr.type.element_ty),
  155. )
  156. p = tl.where(keep, p, 0.0)
  157. elif RETURN_ENCODED_SOFTMAX:
  158. tl.store(
  159. encoded_softmax_block_ptr,
  160. p.to(encoded_softmax_block_ptr.type.element_ty),
  161. )
  162. # -- update output accumulator --
  163. alpha = tl.math.exp2(m_i - m_ij)
  164. acc = acc * alpha[:, None]
  165. if not PRE_LOAD_V:
  166. v = load_fn(
  167. V_block_ptr,
  168. MASK_STEPS and (n_extra_tokens != 0),
  169. PADDED_HEAD,
  170. "zero",
  171. )
  172. # -- update m_i and l_i
  173. l_i = l_i * alpha + l_ij
  174. # update m_i and l_i
  175. m_i = m_ij
  176. acc += tl.dot(p.to(V_block_ptr.type.element_ty), v)
  177. V_block_ptr = tl.advance(V_block_ptr, (BLOCK_N, 0))
  178. K_block_ptr = tl.advance(K_block_ptr, (0, BLOCK_N))
  179. if bias_ptr is not None:
  180. bias_ptr = tl.advance(bias_ptr, (0, BLOCK_N))
  181. if RETURN_ENCODED_SOFTMAX:
  182. encoded_softmax_block_ptr = tl.advance(encoded_softmax_block_ptr,
  183. (0, BLOCK_N))
  184. return acc, l_i, m_i
  185. @triton.autotune(
  186. configs=[
  187. triton.Config(
  188. {
  189. "BLOCK_M": 256,
  190. "BLOCK_N": 64,
  191. "waves_per_eu": 2,
  192. "PRE_LOAD_V": False,
  193. },
  194. num_stages=1,
  195. num_warps=8,
  196. ),
  197. triton.Config(
  198. {
  199. "BLOCK_M": 128,
  200. "BLOCK_N": 128,
  201. "waves_per_eu": 2,
  202. "PRE_LOAD_V": False,
  203. },
  204. num_stages=1,
  205. num_warps=4,
  206. ),
  207. triton.Config(
  208. {
  209. "BLOCK_M": 256,
  210. "BLOCK_N": 128,
  211. "waves_per_eu": 2,
  212. "PRE_LOAD_V": False,
  213. },
  214. num_stages=1,
  215. num_warps=8,
  216. ),
  217. triton.Config(
  218. {
  219. "BLOCK_M": 128,
  220. "BLOCK_N": 64,
  221. "waves_per_eu": 3,
  222. "PRE_LOAD_V": True,
  223. },
  224. num_stages=1,
  225. num_warps=4,
  226. ),
  227. triton.Config(
  228. {
  229. "BLOCK_M": 128,
  230. "BLOCK_N": 64,
  231. "waves_per_eu": 3,
  232. "PRE_LOAD_V": False,
  233. },
  234. num_stages=1,
  235. num_warps=4,
  236. ),
  237. triton.Config(
  238. {
  239. "BLOCK_M": 64,
  240. "BLOCK_N": 64,
  241. "waves_per_eu": 4,
  242. "PRE_LOAD_V": False,
  243. },
  244. num_stages=1,
  245. num_warps=8,
  246. ),
  247. triton.Config(
  248. {
  249. "BLOCK_M": 32,
  250. "BLOCK_N": 32,
  251. "waves_per_eu": 4,
  252. "PRE_LOAD_V": False,
  253. },
  254. num_stages=1,
  255. num_warps=8,
  256. ),
  257. # TODO: This config fails with head_size not pow2 with data mismatches.
  258. # triton.Config({'BLOCK_M': 32, 'BLOCK_N': 16, 'waves_per_eu': 1,
  259. # 'PRE_LOAD_V': False}, num_stages=1, num_warps=4),
  260. triton.Config(
  261. {
  262. "BLOCK_M": 16,
  263. "BLOCK_N": 16,
  264. "waves_per_eu": 1,
  265. "PRE_LOAD_V": False,
  266. },
  267. num_stages=1,
  268. num_warps=4,
  269. ),
  270. ],
  271. key=["hq", "hk", "IS_CAUSAL", "dropout_p", "BLOCK_DMODEL"],
  272. )
  273. @triton.jit
  274. def attn_fwd(
  275. Q,
  276. K,
  277. V,
  278. bias,
  279. sm_scale,
  280. L,
  281. Out,
  282. stride_qz,
  283. stride_qh,
  284. stride_qm,
  285. stride_qk,
  286. stride_kz,
  287. stride_kh,
  288. stride_kn,
  289. stride_kk,
  290. stride_vz,
  291. stride_vh,
  292. stride_vk,
  293. stride_vn,
  294. stride_oz,
  295. stride_oh,
  296. stride_om,
  297. stride_on,
  298. stride_bz,
  299. stride_bh,
  300. stride_bm,
  301. stride_bn,
  302. cu_seqlens_q,
  303. cu_seqlens_k,
  304. dropout_p,
  305. philox_seed,
  306. philox_offset_base,
  307. encoded_softmax,
  308. hq,
  309. hk,
  310. ACTUAL_BLOCK_DMODEL: tl.constexpr,
  311. MAX_SEQLENS_Q: tl.constexpr,
  312. MAX_SEQLENS_K: tl.constexpr,
  313. VARLEN: tl.constexpr,
  314. IS_CAUSAL: tl.constexpr,
  315. BLOCK_M: tl.constexpr,
  316. BLOCK_DMODEL: tl.constexpr,
  317. BLOCK_N: tl.constexpr,
  318. PRE_LOAD_V: tl.constexpr,
  319. BIAS_TYPE: tl.constexpr,
  320. ENABLE_DROPOUT: tl.constexpr,
  321. RETURN_ENCODED_SOFTMAX: tl.constexpr,
  322. ):
  323. start_m = tl.program_id(0)
  324. off_h_q = tl.program_id(1)
  325. off_z = tl.program_id(2)
  326. offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
  327. offs_n = tl.arange(0, BLOCK_N)
  328. if VARLEN:
  329. cu_seqlens_q_start = tl.load(cu_seqlens_q + off_z)
  330. cu_seqlens_q_end = tl.load(cu_seqlens_q + off_z + 1)
  331. seqlen_q = cu_seqlens_q_end - cu_seqlens_q_start
  332. # We have a one-size-fits-all grid in id(0). Some seqlens might be too
  333. # small for all start_m so for those we return early.
  334. if start_m * BLOCK_M > seqlen_q:
  335. return
  336. cu_seqlens_k_start = tl.load(cu_seqlens_k + off_z)
  337. cu_seqlens_k_end = tl.load(cu_seqlens_k + off_z + 1)
  338. seqlen_k = cu_seqlens_k_end - cu_seqlens_k_start
  339. else:
  340. cu_seqlens_q_start = 0
  341. cu_seqlens_k_start = 0
  342. seqlen_q = MAX_SEQLENS_Q
  343. seqlen_k = MAX_SEQLENS_K
  344. # Now we compute whether we need to exit early due to causal masking.
  345. # This is because for seqlen_q > seqlen_k, M rows of the attn scores
  346. # are completely masked, resulting in 0s written to the output, and
  347. # inf written to LSE. We don't need to do any GEMMs in this case.
  348. # This block of code determines what N is, and if this WG is operating
  349. # on those M rows.
  350. n_blocks = cdiv_fn(seqlen_k, BLOCK_N)
  351. if IS_CAUSAL:
  352. # If seqlen_q == seqlen_k, the attn scores are a square matrix.
  353. # If seqlen_q != seqlen_k, attn scores are rectangular which means
  354. # the causal mask boundary is bottom right aligned, and ends at either
  355. # the top edge (seqlen_q < seqlen_k) or left edge.
  356. # This captures the decrease in n_blocks if we have a rectangular attn
  357. # matrix
  358. n_blocks_seqlen = cdiv_fn(
  359. (start_m + 1) * BLOCK_M + seqlen_k - seqlen_q, BLOCK_N)
  360. # This is what adjusts the block_max for the current WG, only
  361. # if IS_CAUSAL. Otherwise we want to always iterate through all n_blocks
  362. n_blocks = min(n_blocks, n_blocks_seqlen)
  363. # If we have no blocks after adjusting for seqlen deltas, this WG is
  364. # part of the blocks that are all 0. We exit early.
  365. if n_blocks <= 0:
  366. o_offset = (off_z * stride_oz + cu_seqlens_q_start * stride_om +
  367. off_h_q * stride_oh)
  368. O_block_ptr = tl.make_block_ptr(
  369. base=Out + o_offset,
  370. shape=(seqlen_q, BLOCK_DMODEL),
  371. strides=(stride_om, stride_on),
  372. offsets=(start_m * BLOCK_M, 0),
  373. block_shape=(BLOCK_M, BLOCK_DMODEL),
  374. order=(1, 0),
  375. )
  376. acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=Out.type.element_ty)
  377. # We still need to write 0s to the result
  378. # tl.store(O_block_ptr,
  379. # acc.to(Out.type.element_ty), boundary_check=(0,1))
  380. # l_ptrs = L + off_z * hq * MAX_SEQLENS_Q + off_h_q * MAX_SEQLENS_Q
  381. # + offs_m
  382. # We store inf to LSE, not -inf because in the bwd pass,
  383. # we subtract this
  384. # from qk which makes it -inf, such that exp(qk - inf) = 0
  385. # for these masked blocks.
  386. # l = tl.full([BLOCK_M], value=float("inf"), dtype=tl.float32)
  387. # tl.store(l_ptrs, l)
  388. # TODO: Should dropout and return encoded softmax be handled here?
  389. return
  390. is_mqa = hq != hk
  391. if is_mqa: # noqa: SIM108
  392. off_h_k = off_h_q % hk
  393. else:
  394. off_h_k = off_h_q
  395. n_extra_tokens = 0
  396. if seqlen_k < BLOCK_N:
  397. n_extra_tokens = BLOCK_N - seqlen_k
  398. elif seqlen_k % BLOCK_N:
  399. n_extra_tokens = seqlen_k % BLOCK_N
  400. padded_head = ACTUAL_BLOCK_DMODEL != BLOCK_DMODEL
  401. # Compute pointers for all the tensors used in this kernel.
  402. q_offset = (off_z * stride_qz + off_h_q * stride_qh +
  403. cu_seqlens_q_start * stride_qm)
  404. Q_block_ptr = tl.make_block_ptr(
  405. base=Q + q_offset,
  406. shape=(seqlen_q, ACTUAL_BLOCK_DMODEL),
  407. strides=(stride_qm, stride_qk),
  408. offsets=(start_m * BLOCK_M, 0),
  409. block_shape=(BLOCK_M, BLOCK_DMODEL),
  410. order=(1, 0),
  411. )
  412. k_offset = (off_z * stride_kz + off_h_k * stride_kh +
  413. cu_seqlens_k_start * stride_kn)
  414. K_block_ptr = tl.make_block_ptr(
  415. base=K + k_offset,
  416. shape=(ACTUAL_BLOCK_DMODEL, seqlen_k),
  417. strides=(stride_kk, stride_kn),
  418. offsets=(0, 0),
  419. block_shape=(BLOCK_DMODEL, BLOCK_N),
  420. order=(0, 1),
  421. )
  422. v_offset = (off_z * stride_vz + off_h_k * stride_vh +
  423. cu_seqlens_k_start * stride_vk)
  424. V_block_ptr = tl.make_block_ptr(
  425. base=V + v_offset,
  426. shape=(seqlen_k, ACTUAL_BLOCK_DMODEL),
  427. strides=(stride_vk, stride_vn),
  428. offsets=(0, 0),
  429. block_shape=(BLOCK_N, BLOCK_DMODEL),
  430. order=(1, 0),
  431. )
  432. if BIAS_TYPE != 0:
  433. bias_ptr = tl.make_block_ptr(
  434. base=bias + off_h_q * stride_bh,
  435. shape=(seqlen_q, seqlen_k),
  436. strides=(stride_bm, stride_bn),
  437. offsets=(start_m * BLOCK_M, 0),
  438. block_shape=(BLOCK_M, BLOCK_N),
  439. order=(1, 0),
  440. )
  441. else:
  442. bias_ptr = None
  443. if ENABLE_DROPOUT:
  444. batch_philox_offset = philox_offset_base \
  445. + (off_z * hq + off_h_q) \
  446. * seqlen_q * seqlen_k
  447. else:
  448. batch_philox_offset = 0
  449. # We can ask to return the dropout mask without actually doing any dropout.
  450. # In this case, we return an invalid pointer so indicate the mask is not i
  451. # valid.
  452. # TODO: Fix encoded softmax. It currently uses just h_q in the base offset.
  453. if RETURN_ENCODED_SOFTMAX:
  454. encoded_softmax_block_ptr = tl.make_block_ptr(
  455. base=encoded_softmax + off_h_q * seqlen_q * seqlen_k,
  456. shape=(seqlen_q, seqlen_k),
  457. strides=(seqlen_k, 1),
  458. offsets=(start_m * BLOCK_M, 0),
  459. block_shape=(BLOCK_M, BLOCK_N),
  460. order=(1, 0),
  461. )
  462. else:
  463. encoded_softmax_block_ptr = 0
  464. # initialize pointer to m and l
  465. m_i = tl.full([BLOCK_M], float("-inf"), dtype=tl.float32)
  466. l_i = tl.full([BLOCK_M], 1.0, dtype=tl.float32)
  467. acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32)
  468. # scale sm_scale by log_2(e) and use 2^x in the loop as we do not
  469. # have native e^x support in HW.
  470. qk_scale = sm_scale * 1.44269504089
  471. # Q is loaded once at the beginning and shared by all N blocks.
  472. q = load_fn(Q_block_ptr, True, padded_head, "zero")
  473. q = (q * qk_scale).to(Q_block_ptr.type.element_ty)
  474. # Here we compute how many full and masked blocks we have.
  475. padded_block_k = n_extra_tokens != 0
  476. is_modulo_mn = not padded_block_k and (seqlen_q % BLOCK_M == 0)
  477. if IS_CAUSAL:
  478. # There are always at least BLOCK_M // BLOCK_N masked blocks.
  479. # Additionally there might be one more due to dissimilar seqlens.
  480. masked_blocks = BLOCK_M // BLOCK_N + (not is_modulo_mn)
  481. else:
  482. # Padding on Q does not need to be masked in the FA loop.
  483. masked_blocks = padded_block_k
  484. # if IS_CAUSAL, not is_modulo_mn does not always result in an additional
  485. # block. In this case we might exceed n_blocks so pick the min.
  486. masked_blocks = min(masked_blocks, n_blocks)
  487. n_full_blocks = n_blocks - masked_blocks
  488. block_min = 0
  489. block_max = n_blocks * BLOCK_N
  490. # Compute for full blocks. Here we set causal to false regardless of its
  491. # value because there is no masking. Similarly we do not need padding.
  492. if n_full_blocks > 0:
  493. block_max = (n_blocks - masked_blocks) * BLOCK_N
  494. acc, l_i, m_i = _attn_fwd_inner(
  495. acc,
  496. l_i,
  497. m_i,
  498. q,
  499. K_block_ptr,
  500. V_block_ptr,
  501. start_m,
  502. seqlen_k,
  503. dropout_p,
  504. philox_seed,
  505. batch_philox_offset,
  506. encoded_softmax_block_ptr,
  507. # _, _, offs_n_causal, masked_blocks, n_extra_tokens, _
  508. block_min,
  509. block_max,
  510. 0,
  511. 0,
  512. 0,
  513. bias_ptr,
  514. # IS_CAUSAL, ....
  515. False,
  516. BLOCK_M,
  517. BLOCK_DMODEL,
  518. BLOCK_N,
  519. offs_m,
  520. offs_n,
  521. # _, MASK_STEPS, ...
  522. PRE_LOAD_V,
  523. False,
  524. ENABLE_DROPOUT,
  525. RETURN_ENCODED_SOFTMAX,
  526. padded_head,
  527. )
  528. block_min = block_max
  529. block_max = n_blocks * BLOCK_N
  530. tl.debug_barrier()
  531. # Remaining blocks, if any, are full / not masked.
  532. if masked_blocks > 0:
  533. offs_n_causal = offs_n + (seqlen_q - seqlen_k) if IS_CAUSAL else 0
  534. K_block_ptr = tl.advance(K_block_ptr, (0, n_full_blocks * BLOCK_N))
  535. V_block_ptr = tl.advance(V_block_ptr, (n_full_blocks * BLOCK_N, 0))
  536. if bias_ptr is not None:
  537. bias_ptr = tl.advance(bias_ptr, (0, n_full_blocks * BLOCK_N))
  538. if RETURN_ENCODED_SOFTMAX:
  539. encoded_softmax_block_ptr = tl.advance(encoded_softmax_block_ptr,
  540. (0, n_full_blocks))
  541. acc, l_i, m_i = _attn_fwd_inner(
  542. acc,
  543. l_i,
  544. m_i,
  545. q,
  546. K_block_ptr,
  547. V_block_ptr,
  548. start_m,
  549. seqlen_k,
  550. dropout_p,
  551. philox_seed,
  552. batch_philox_offset,
  553. encoded_softmax_block_ptr,
  554. block_min,
  555. block_max,
  556. offs_n_causal,
  557. masked_blocks,
  558. n_extra_tokens,
  559. bias_ptr,
  560. IS_CAUSAL,
  561. BLOCK_M,
  562. BLOCK_DMODEL,
  563. BLOCK_N,
  564. offs_m,
  565. offs_n,
  566. # _, MASK_STEPS, ...
  567. PRE_LOAD_V,
  568. True,
  569. ENABLE_DROPOUT,
  570. RETURN_ENCODED_SOFTMAX,
  571. padded_head,
  572. )
  573. # epilogue
  574. acc = acc / l_i[:, None]
  575. if ENABLE_DROPOUT:
  576. acc = acc / (1 - dropout_p)
  577. # If seqlen_q > seqlen_k but the delta is not a multiple of BLOCK_M,
  578. # then we have one block with a row of all NaNs which come from computing
  579. # softmax over a row of all -infs (-inf - inf = NaN). We check for that here
  580. # and store 0s where there are NaNs as these rows should've been zeroed out.
  581. end_m_idx = (start_m + 1) * BLOCK_M
  582. start_m_idx = start_m * BLOCK_M
  583. causal_start_idx = seqlen_q - seqlen_k
  584. acc = acc.to(Out.type.element_ty)
  585. if IS_CAUSAL: # noqa: SIM102
  586. if causal_start_idx > start_m_idx and causal_start_idx < end_m_idx:
  587. out_mask_boundary = tl.full((BLOCK_DMODEL, ),
  588. causal_start_idx,
  589. dtype=tl.int32)
  590. mask_m_offsets = start_m_idx + tl.arange(0, BLOCK_M)
  591. out_ptrs_mask = (mask_m_offsets[:, None] >=
  592. out_mask_boundary[None, :])
  593. z = 0.0
  594. acc = tl.where(out_ptrs_mask, acc, z.to(acc.type.element_ty))
  595. # write back LSE
  596. # l_ptrs = L + off_z * hq * MAX_SEQLENS_Q + off_h_q * MAX_SEQLENS_Q + offs_m
  597. # If seqlen_q not multiple of BLOCK_M, we need to mask out the last
  598. # few rows. This is only true for the last M block. For others,
  599. # overflow_size will be -ve
  600. # overflow_size = end_m_idx - seqlen_q
  601. # if overflow_size > 0:
  602. # boundary = tl.full((BLOCK_M,), BLOCK_M - overflow_size, dtype=tl.int32)
  603. # # This is a > check because mask being 0 blocks the store.
  604. # l_ptrs_mask = boundary > tl.arange(0, BLOCK_M)
  605. # tl.store(l_ptrs, m_i + tl.math.log2(l_i), mask=l_ptrs_mask)
  606. # else:
  607. # tl.store(l_ptrs, m_i + tl.math.log2(l_i))
  608. # write back O
  609. o_offset = (off_z * stride_oz + cu_seqlens_q_start * stride_om +
  610. off_h_q * stride_oh)
  611. O_block_ptr = tl.make_block_ptr(
  612. base=Out + o_offset,
  613. shape=(seqlen_q, ACTUAL_BLOCK_DMODEL),
  614. strides=(stride_om, stride_on),
  615. offsets=(start_m * BLOCK_M, 0),
  616. block_shape=(BLOCK_M, BLOCK_DMODEL),
  617. order=(1, 0),
  618. )
  619. # Need boundary check on this to make sure the padding from the
  620. # Q and KV tensors in both dims are not part of what we store back.
  621. # TODO: Do the boundary check optionally.
  622. tl.store(O_block_ptr, acc, boundary_check=(0, 1))
  623. def check_args(
  624. q,
  625. k,
  626. v,
  627. o,
  628. varlen=True,
  629. max_seqlens=None,
  630. cu_seqlens_q=None,
  631. cu_seqlens_k=None,
  632. ):
  633. assert q.dim() == k.dim() and q.dim() == v.dim()
  634. if varlen:
  635. assert q.dim() == 3
  636. total_q, nheads_q, head_size = q.shape
  637. total_k, nheads_k, _ = k.shape
  638. assert cu_seqlens_q is not None
  639. assert cu_seqlens_k is not None
  640. assert len(cu_seqlens_q) == len(cu_seqlens_k)
  641. else:
  642. assert q.dim() == 4
  643. batch, nheads_q, seqlen_q, head_size = q.shape
  644. _, nheads_k, seqlen_k, _ = k.shape
  645. assert max_seqlens > 0
  646. assert k.shape == v.shape
  647. assert q.shape[-1] == k.shape[-1] and q.shape[-1] == v.shape[-1]
  648. # TODO: Change assert if we support qkl f8 and v f16
  649. assert q.dtype == k.dtype and q.dtype == v.dtype
  650. assert head_size <= 256
  651. assert o.shape == q.shape
  652. assert (nheads_q % nheads_k) == 0
  653. class _attention(torch.autograd.Function):
  654. @staticmethod
  655. def forward(
  656. ctx,
  657. q,
  658. k,
  659. v,
  660. o,
  661. cu_seqlens_q,
  662. cu_seqlens_k,
  663. max_seqlens_q,
  664. max_seqlens_k,
  665. causal=False,
  666. sm_scale=1.0,
  667. bias=None,
  668. ):
  669. if o is None:
  670. o = torch.empty_like(q, dtype=v.dtype)
  671. check_args(
  672. q,
  673. k,
  674. v,
  675. o,
  676. varlen=True,
  677. cu_seqlens_q=cu_seqlens_q,
  678. cu_seqlens_k=cu_seqlens_k,
  679. )
  680. if True: # varlen
  681. total_q, nheads_q, head_size = q.shape
  682. total_k, nheads_k, _ = k.shape
  683. batch = len(cu_seqlens_q) - 1
  684. q_strides = (0, q.stride(1), q.stride(0), q.stride(2))
  685. k_strides = (0, k.stride(1), k.stride(0), k.stride(2))
  686. v_strides = (0, v.stride(1), v.stride(0), v.stride(2))
  687. o_strides = (0, o.stride(1), o.stride(0), o.stride(2))
  688. else:
  689. batch, seqlen_q, nheads_q, head_size = q.shape
  690. _, seqlen_k, nheads_k, _ = k.shape
  691. q_strides = (q.stride(0), q.stride(2), q.stride(1), q.stride(3))
  692. k_strides = (k.stride(0), k.stride(2), k.stride(1), k.stride(3))
  693. v_strides = (v.stride(0), v.stride(2), v.stride(1), v.stride(3))
  694. o_strides = (o.stride(0), o.stride(2), o.stride(1), o.stride(3))
  695. # Get closest power of 2 over or equal to 32.
  696. unpadded_head_dims = {32, 64, 128, 256}
  697. if head_size not in unpadded_head_dims:
  698. padded_d_model = None
  699. for i in unpadded_head_dims:
  700. if i > head_size:
  701. padded_d_model = i
  702. break
  703. assert padded_d_model is not None
  704. else:
  705. padded_d_model = head_size
  706. grid = lambda META: (
  707. triton.cdiv(max_seqlens_q, META["BLOCK_M"]),
  708. nheads_q,
  709. batch,
  710. )
  711. encoded_softmax = None
  712. # Seed the RNG so we get reproducible results for testing.
  713. philox_seed = 0x1BF52
  714. philox_offset = 0x1D4B42
  715. if bias is not None:
  716. bias_strides = (
  717. bias.stride(0),
  718. bias.stride(1),
  719. bias.stride(2),
  720. bias.stride(3),
  721. )
  722. else:
  723. bias_strides = (0, 0, 0, 0)
  724. attn_fwd[grid](
  725. q,
  726. k,
  727. v,
  728. bias,
  729. sm_scale,
  730. None,
  731. o,
  732. *q_strides,
  733. *k_strides,
  734. *v_strides,
  735. *o_strides,
  736. *bias_strides,
  737. cu_seqlens_q,
  738. cu_seqlens_k,
  739. dropout_p=0.0,
  740. philox_seed=philox_seed,
  741. philox_offset_base=philox_offset,
  742. encoded_softmax=encoded_softmax,
  743. hq=nheads_q,
  744. hk=nheads_k,
  745. ACTUAL_BLOCK_DMODEL=head_size,
  746. MAX_SEQLENS_Q=max_seqlens_q,
  747. MAX_SEQLENS_K=max_seqlens_k,
  748. IS_CAUSAL=causal,
  749. VARLEN=True,
  750. BLOCK_DMODEL=padded_d_model,
  751. BIAS_TYPE=0 if bias is None else 1,
  752. ENABLE_DROPOUT=False,
  753. RETURN_ENCODED_SOFTMAX=False,
  754. )
  755. ctx.grid = grid
  756. ctx.sm_scale = sm_scale
  757. ctx.BLOCK_DMODEL = head_size
  758. ctx.causal = causal
  759. ctx.dropout_p = 0.0
  760. ctx.philox_seed = philox_seed
  761. ctx.philox_offset = philox_offset
  762. ctx.encoded_softmax = encoded_softmax
  763. ctx.return_encoded_softmax = False
  764. return o, encoded_softmax
  765. triton_attention = _attention.apply