Advertisement
MartinFajcik

triton_flash_attn_fn

Oct 4th, 2023
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 37.78 KB | None | 0 0
  1. from typing import Optional, Tuple
  2.  
  3. from einops import rearrange
  4.  
  5. """
  6. Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
  7. update imports to use 'triton_pre_mlir'
  8.  
  9. Differences between this Triton version and the CUDA version:
  10. - Triton version doesn't support dropout.
  11. - Triton forward is generally faster than CUDA forward, while Triton backward is
  12. generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
  13. than CUDA forward + backward.
  14. - Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
  15. - Triton version supports attention bias, while CUDA version doesn't.
  16. """
  17.  
  18. import math
  19. import torch._dynamo
  20. import torch
  21.  
  22. import triton_pre_mlir as triton
  23. import triton_pre_mlir.language as tl
  24.  
  25.  
  26. # Disabling autotune for now, set num_warps=4 if headdim=64 and num_warps=8 if headdim=128
  27. # @triton.autotune(
  28. #     configs=[
  29. #         triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1),
  30. #         # This config has a race condition when EVEN_M == False, disabling it for now.
  31. #         # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1),
  32. #     ],
  33. #     key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM']
  34. # )
  35. @triton.heuristics(
  36.     {
  37.         "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
  38.         "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
  39.         "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
  40.     }
  41. )
  42. @triton.jit
  43. def _fwd_kernel(
  44.         Q, K, V, Bias, Out,
  45.         Lse, TMP,  # NOTE: TMP is a scratchpad buffer to workaround a compiler bug
  46.         softmax_scale,
  47.         stride_qb, stride_qh, stride_qm,
  48.         stride_kb, stride_kh, stride_kn,
  49.         stride_vb, stride_vh, stride_vn,
  50.         stride_bb, stride_bh, stride_bm,
  51.         stride_ob, stride_oh, stride_om,
  52.         nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim,
  53.         CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K,
  54.         BIAS_TYPE: tl.constexpr,
  55.         IS_CAUSAL: tl.constexpr,
  56.         BLOCK_HEADDIM: tl.constexpr,
  57.         EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
  58.         BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
  59. ):
  60.     start_m = tl.program_id(0)
  61.     off_hb = tl.program_id(1)
  62.     off_b = off_hb // nheads
  63.     off_h = off_hb % nheads
  64.     # off_b = tl.program_id(1)
  65.     # off_h = tl.program_id(2)
  66.     # off_hb = off_b * nheads + off_h
  67.     # initialize offsets
  68.     offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
  69.     offs_n = tl.arange(0, BLOCK_N)
  70.     offs_d = tl.arange(0, BLOCK_HEADDIM)
  71.     # Initialize pointers to Q, K, V
  72.     # Adding parenthesis around indexing might use int32 math instead of int64 math?
  73.     # https://github.com/openai/triton/issues/741
  74.     # I'm seeing a tiny bit of difference (5-7us)
  75.     q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
  76.     k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
  77.     v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
  78.     if BIAS_TYPE == 'vector':
  79.         b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
  80.     elif BIAS_TYPE == 'matrix':
  81.         b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
  82.     # initialize pointer to m and l
  83.     t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
  84.     lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
  85.     m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
  86.     acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
  87.     # load q: it will stay in SRAM throughout
  88.     # [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call
  89.     # tl.load(q_ptrs), we get the wrong output!
  90.     if EVEN_M & EVEN_N:
  91.         if EVEN_HEADDIM:
  92.             q = tl.load(q_ptrs)
  93.         else:
  94.             q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
  95.     else:
  96.         if EVEN_HEADDIM:
  97.             q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
  98.         else:
  99.             q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
  100.                         other=0.0)
  101.     # loop over k, v and update accumulator
  102.     end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
  103.     for start_n in range(0, end_n, BLOCK_N):
  104.         start_n = tl.multiple_of(start_n, BLOCK_N)
  105.         # -- compute qk ----
  106.         if EVEN_N & EVEN_M:  # If we just do "if EVEN_N", there seems to be some race condition
  107.             if EVEN_HEADDIM:
  108.                 k = tl.load(k_ptrs + start_n * stride_kn)
  109.             else:
  110.                 k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
  111.         else:
  112.             if EVEN_HEADDIM:
  113.                 k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k,
  114.                             other=0.0)
  115.             else:
  116.                 k = tl.load(k_ptrs + start_n * stride_kn,
  117.                             mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
  118.                             other=0.0)
  119.         qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
  120.         qk += tl.dot(q, k, trans_b=True)
  121.         # Trying to combine the two masks seem to make the result wrong
  122.         if not EVEN_N:  # Need to mask out otherwise the softmax is wrong
  123.             qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float("-inf"))
  124.         if IS_CAUSAL:
  125.             qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float("-inf"))
  126.         if BIAS_TYPE != 'none':
  127.             if BIAS_TYPE == 'vector':
  128.                 if EVEN_N:
  129.                     bias = tl.load(b_ptrs + start_n).to(tl.float32)
  130.                 else:
  131.                     bias = tl.load(b_ptrs + start_n, mask=(start_n + offs_n) < seqlen_k, other=0.0).to(tl.float32)
  132.                 bias = bias[None, :]
  133.             elif BIAS_TYPE == 'matrix':
  134.                 if EVEN_M & EVEN_N:
  135.                     bias = tl.load(b_ptrs + start_n).to(tl.float32)
  136.                 else:
  137.                     bias = tl.load(b_ptrs + start_n,
  138.                                    mask=(offs_m[:, None] < seqlen_q)
  139.                                         & ((start_n + offs_n)[None, :] < seqlen_k),
  140.                                    other=0.0).to(tl.float32)
  141.             # Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler
  142.             # can then fuse the mult and add into an fma instruction. But if we have bias we need to
  143.             # to multiply with softmax_scale here.
  144.             qk = qk * softmax_scale + bias
  145.             m_ij = tl.maximum(tl.max(qk, 1), lse_i)
  146.             p = tl.exp(qk - m_ij[:, None])
  147.         else:
  148.             m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
  149.             p = tl.exp(qk * softmax_scale - m_ij[:, None])
  150.         l_ij = tl.sum(p, 1)
  151.  
  152.         # scale acc_o
  153.         acc_o_scale = tl.exp(m_i - m_ij)
  154.  
  155.         # # -- update output accumulator --
  156.         # BUG: have to store and immediately load
  157.         tl.store(t_ptrs, acc_o_scale)
  158.         acc_o_scale = tl.load(t_ptrs)
  159.         acc_o = acc_o * acc_o_scale[:, None]
  160.         # update acc_o
  161.         if EVEN_N & EVEN_M:  # If we just do "if EVEN_N", there seems to be some race condition
  162.             if EVEN_HEADDIM:
  163.                 v = tl.load(v_ptrs + start_n * stride_vn)
  164.             else:
  165.                 v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
  166.         else:
  167.             if EVEN_HEADDIM:
  168.                 v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k,
  169.                             other=0.0)
  170.             else:
  171.                 v = tl.load(v_ptrs + start_n * stride_vn,
  172.                             mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
  173.                             other=0.0)
  174.         p = p.to(v.dtype)
  175.         acc_o += tl.dot(p, v)
  176.  
  177.         # -- update statistics
  178.         m_i = m_ij
  179.         l_i_new = tl.exp(lse_i - m_ij) + l_ij
  180.         lse_i = m_ij + tl.log(l_i_new)
  181.  
  182.     o_scale = tl.exp(m_i - lse_i)
  183.     # BUG: have to store and immediately load
  184.     tl.store(t_ptrs, o_scale)
  185.     o_scale = tl.load(t_ptrs)
  186.     acc_o = acc_o * o_scale[:, None]
  187.     # rematerialize offsets to save registers
  188.     start_m = tl.program_id(0)
  189.     offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
  190.     # write back l and m
  191.     lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
  192.     tl.store(lse_ptrs, lse_i)
  193.     # initialize pointers to output
  194.     offs_d = tl.arange(0, BLOCK_HEADDIM)
  195.     out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
  196.     if EVEN_M:
  197.         if EVEN_HEADDIM:
  198.             tl.store(out_ptrs, acc_o)
  199.         else:
  200.             tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
  201.     else:
  202.         if EVEN_HEADDIM:
  203.             tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
  204.         else:
  205.             tl.store(out_ptrs, acc_o,
  206.                      mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
  207.  
  208.  
  209. @triton.jit
  210. def _bwd_preprocess_do_o_dot(
  211.         Out, DO, Delta,
  212.         stride_ob, stride_oh, stride_om,
  213.         stride_dob, stride_doh, stride_dom,
  214.         nheads, seqlen_q, seqlen_q_rounded, headdim,
  215.         BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr,
  216. ):
  217.     start_m = tl.program_id(0)
  218.     off_hb = tl.program_id(1)
  219.     off_b = off_hb // nheads
  220.     off_h = off_hb % nheads
  221.     # initialize offsets
  222.     offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
  223.     offs_d = tl.arange(0, BLOCK_HEADDIM)
  224.     # load
  225.     o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :],
  226.                 mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
  227.     do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :],
  228.                  mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
  229.     delta = tl.sum(o * do, axis=1)
  230.     # write-back
  231.     tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
  232.  
  233.  
  234. @triton.jit
  235. def _bwd_store_dk_dv(
  236.         dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim,
  237.         EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
  238. ):
  239.     # [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False,
  240.     # if we just call tl.store(dv_ptrs), there's a race condition
  241.     if EVEN_N & EVEN_M:
  242.         if EVEN_HEADDIM:
  243.             tl.store(dv_ptrs, dv)
  244.             tl.store(dk_ptrs, dk)
  245.         else:
  246.             tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
  247.             tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
  248.     else:
  249.         if EVEN_HEADDIM:
  250.             tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
  251.             tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
  252.         else:
  253.             tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
  254.             tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
  255.  
  256.  
  257. @triton.jit
  258. def _bwd_kernel_one_col_block(
  259.         start_n,
  260.         Q, K, V, Bias,
  261.         DO, DQ, DK, DV,
  262.         LSE, D,
  263.         softmax_scale,
  264.         stride_qm, stride_kn, stride_vn, stride_bm,
  265.         stride_dom, stride_dqm, stride_dkn, stride_dvn,
  266.         seqlen_q, seqlen_k, headdim,
  267.         ATOMIC_ADD: tl.constexpr,
  268.         BIAS_TYPE: tl.constexpr,
  269.         IS_CAUSAL: tl.constexpr,
  270.         BLOCK_HEADDIM: tl.constexpr,
  271.         EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
  272.         BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
  273. ):
  274.     # We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N)
  275.     begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M
  276.     # initialize row/col offsets
  277.     offs_qm = begin_m + tl.arange(0, BLOCK_M)
  278.     offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
  279.     offs_m = tl.arange(0, BLOCK_M)
  280.     offs_d = tl.arange(0, BLOCK_HEADDIM)
  281.     # initialize pointers to value-like data
  282.     q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
  283.     k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
  284.     v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
  285.     do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
  286.     dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
  287.     if BIAS_TYPE == 'vector':
  288.         b_ptrs = Bias + offs_n
  289.     elif BIAS_TYPE == 'matrix':
  290.         b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
  291.     # initialize dv and dk
  292.     dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
  293.     dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
  294.     # There seems to be some problem with Triton pipelining that makes results wrong for
  295.     # headdim=64, seqlen=(113, 255), bias_type='matrix'. In this case the for loop
  296.     # may have zero step, and pipelining with the bias matrix could screw it up.
  297.     # So we just exit early.
  298.     if begin_m >= seqlen_q:
  299.         dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
  300.         dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
  301.         _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim,
  302.                          EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
  303.         return
  304.     # k and v stay in SRAM throughout
  305.     # [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False,
  306.     # if we just call tl.load(k_ptrs), we get the wrong output!
  307.     if EVEN_N & EVEN_M:
  308.         if EVEN_HEADDIM:
  309.             k = tl.load(k_ptrs)
  310.             v = tl.load(v_ptrs)
  311.         else:
  312.             k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
  313.             v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
  314.     else:
  315.         if EVEN_HEADDIM:
  316.             k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
  317.             v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
  318.         else:
  319.             k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
  320.                         other=0.0)
  321.             v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
  322.                         other=0.0)
  323.     # loop over rows
  324.     num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
  325.     for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
  326.         start_m = tl.multiple_of(start_m, BLOCK_M)
  327.         offs_m_curr = start_m + offs_m
  328.         # load q, k, v, do on-chip
  329.         # Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117)
  330.         if EVEN_M & EVEN_HEADDIM:
  331.             q = tl.load(q_ptrs)
  332.         else:
  333.             if EVEN_HEADDIM:
  334.                 q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
  335.             else:
  336.                 q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
  337.                                          & (offs_d[None, :] < headdim), other=0.0)
  338.         # recompute p = softmax(qk, dim=-1).T
  339.         qk = tl.dot(q, k, trans_b=True)
  340.         # Trying to combine the two masks seem to make the result wrong
  341.         if not EVEN_N:  # Need to mask out otherwise the softmax is wrong
  342.             qk = tl.where(offs_n[None, :] < seqlen_k, qk, float("-inf"))
  343.         if IS_CAUSAL:
  344.             qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk, float("-inf"))
  345.         if BIAS_TYPE != 'none':
  346.             tl.debug_barrier()  # Race condition otherwise
  347.             if BIAS_TYPE == 'vector':
  348.                 if EVEN_N:
  349.                     bias = tl.load(b_ptrs).to(tl.float32)
  350.                 else:
  351.                     bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
  352.                 bias = bias[None, :]
  353.             elif BIAS_TYPE == 'matrix':
  354.                 if EVEN_M & EVEN_N:
  355.                     bias = tl.load(b_ptrs).to(tl.float32)
  356.                 else:
  357.                     bias = tl.load(b_ptrs,
  358.                                    mask=(offs_m_curr[:, None] < seqlen_q)
  359.                                         & (offs_n[None, :] < seqlen_k),
  360.                                    other=0.0).to(tl.float32)
  361.             qk = qk * softmax_scale + bias
  362.         # There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong.
  363.         # Also wrong for headdim=64.
  364.         if not (EVEN_M & EVEN_HEADDIM):
  365.             tl.debug_barrier()
  366.         lse_i = tl.load(LSE + offs_m_curr)
  367.         if BIAS_TYPE == 'none':
  368.             p = tl.exp(qk * softmax_scale - lse_i[:, None])
  369.         else:
  370.             p = tl.exp(qk - lse_i[:, None])
  371.         # compute dv
  372.         # [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call
  373.         # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs
  374.         # in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512,
  375.         # the output is correct.
  376.         if EVEN_M & EVEN_HEADDIM:
  377.             do = tl.load(do_ptrs)
  378.         else:
  379.             # [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask.
  380.             do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
  381.                                        & (offs_d[None, :] < headdim), other=0.0)
  382.         # if EVEN_M:
  383.         #     if EVEN_HEADDIM:
  384.         #         do = tl.load(do_ptrs)
  385.         #     else:
  386.         #         do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
  387.         # else:
  388.         #     if EVEN_HEADDIM:
  389.         #         do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
  390.         #     else:
  391.         #         do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
  392.         #                                    & (offs_d[None, :] < headdim), other=0.0)
  393.         dv += tl.dot(p.to(do.dtype), do, trans_a=True)
  394.         # compute dp = dot(v, do)
  395.         # There seems to be a race condition when headdim=48/96, and dq, dk are wrong.
  396.         # Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True
  397.         # Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False
  398.         if not (EVEN_M & EVEN_HEADDIM):
  399.             tl.debug_barrier()
  400.         dp = tl.dot(do, v, trans_b=True)
  401.         # There's a race condition for headdim=48
  402.         if not EVEN_HEADDIM:
  403.             tl.debug_barrier()
  404.         # compute ds = p * (dp - delta[:, None])
  405.         # Putting the subtraction after the dp matmul (instead of before) is slightly faster
  406.         Di = tl.load(D + offs_m_curr)
  407.         # Converting ds to q.dtype here reduces register pressure and makes it much faster
  408.         # for BLOCK_HEADDIM=128
  409.         ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
  410.         # compute dk = dot(ds.T, q)
  411.         dk += tl.dot(ds, q, trans_a=True)
  412.         # compute dq
  413.         if not (EVEN_M & EVEN_HEADDIM):  # Otherewise there's a race condition when BIAS_TYPE='matrix'
  414.             tl.debug_barrier()
  415.         if not ATOMIC_ADD:
  416.             if EVEN_M & EVEN_HEADDIM:  # Race condition if we just do EVEN_M
  417.                 dq = tl.load(dq_ptrs, eviction_policy="evict_last")
  418.                 dq += tl.dot(ds, k)
  419.                 tl.store(dq_ptrs, dq, eviction_policy="evict_last")
  420.             else:
  421.                 if EVEN_HEADDIM:
  422.                     dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0,
  423.                                  eviction_policy="evict_last")
  424.                     dq += tl.dot(ds, k)
  425.                     tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q,
  426.                              eviction_policy="evict_last")
  427.                 else:
  428.                     dq = tl.load(dq_ptrs,
  429.                                  mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
  430.                                  other=0.0, eviction_policy="evict_last")
  431.                     dq += tl.dot(ds, k)
  432.                     tl.store(dq_ptrs, dq,
  433.                              mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
  434.                              eviction_policy="evict_last")
  435.         else:  # If we're parallelizing across the seqlen_k dimension
  436.             dq = tl.dot(ds, k)
  437.             if EVEN_M & EVEN_HEADDIM:  # Race condition if we just do EVEN_M
  438.                 tl.atomic_add(dq_ptrs, dq)
  439.             else:
  440.                 if EVEN_HEADDIM:
  441.                     tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
  442.                 else:
  443.                     tl.atomic_add(dq_ptrs, dq,
  444.                                   mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
  445.         # increment pointers
  446.         dq_ptrs += BLOCK_M * stride_dqm
  447.         q_ptrs += BLOCK_M * stride_qm
  448.         do_ptrs += BLOCK_M * stride_dom
  449.         if BIAS_TYPE == 'matrix':
  450.             b_ptrs += BLOCK_M * stride_bm
  451.     # write-back
  452.     dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
  453.     dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
  454.     _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim,
  455.                      EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
  456.  
  457.  
  458. def init_to_zero(name):
  459.     return lambda nargs: nargs[name].zero_()
  460.  
  461.  
  462. @triton.autotune(
  463.     configs=[
  464.         triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1,
  465.                       pre_hook=init_to_zero('DQ')),
  466.         triton.Config({"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1,
  467.                       pre_hook=init_to_zero('DQ')),
  468.         # Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now
  469.         # # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4*
  470.         # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
  471.         # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
  472.         # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
  473.         # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
  474.     ],
  475.     key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'],
  476. )
  477. @triton.heuristics(
  478.     {
  479.         "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
  480.         "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
  481.         "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
  482.     }
  483. )
  484. @triton.jit
  485. def _bwd_kernel(
  486.         Q, K, V, Bias,
  487.         DO, DQ, DK, DV,
  488.         LSE, D,
  489.         softmax_scale,
  490.         stride_qb, stride_qh, stride_qm,
  491.         stride_kb, stride_kh, stride_kn,
  492.         stride_vb, stride_vh, stride_vn,
  493.         stride_bb, stride_bh, stride_bm,
  494.         stride_dob, stride_doh, stride_dom,
  495.         stride_dqb, stride_dqh, stride_dqm,
  496.         stride_dkb, stride_dkh, stride_dkn,
  497.         stride_dvb, stride_dvh, stride_dvn,
  498.         nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim,
  499.         CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K,
  500.         BIAS_TYPE: tl.constexpr,
  501.         IS_CAUSAL: tl.constexpr,
  502.         BLOCK_HEADDIM: tl.constexpr,
  503.         SEQUENCE_PARALLEL: tl.constexpr,
  504.         EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr,
  505.         BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
  506. ):
  507.     off_hb = tl.program_id(1)
  508.     off_b = off_hb // nheads
  509.     off_h = off_hb % nheads
  510.     # offset pointers for batch/head
  511.     Q += off_b * stride_qb + off_h * stride_qh
  512.     K += off_b * stride_kb + off_h * stride_kh
  513.     V += off_b * stride_vb + off_h * stride_vh
  514.     DO += off_b * stride_dob + off_h * stride_doh
  515.     DQ += off_b * stride_dqb + off_h * stride_dqh
  516.     DK += off_b * stride_dkb + off_h * stride_dkh
  517.     DV += off_b * stride_dvb + off_h * stride_dvh
  518.     if BIAS_TYPE != 'none':
  519.         Bias += off_b * stride_bb + off_h * stride_bh
  520.     # pointer to row-wise quantities in value-like data
  521.     D += off_hb * seqlen_q_rounded
  522.     LSE += off_hb * seqlen_q_rounded
  523.     if not SEQUENCE_PARALLEL:
  524.         num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
  525.         for start_n in range(0, num_block_n):
  526.             _bwd_kernel_one_col_block(
  527.                 start_n,
  528.                 Q, K, V, Bias,
  529.                 DO, DQ, DK, DV,
  530.                 LSE, D,
  531.                 softmax_scale,
  532.                 stride_qm, stride_kn, stride_vn, stride_bm,
  533.                 stride_dom, stride_dqm, stride_dkn, stride_dvn,
  534.                 seqlen_q, seqlen_k, headdim,
  535.                 ATOMIC_ADD=False,
  536.                 BIAS_TYPE=BIAS_TYPE,
  537.                 IS_CAUSAL=IS_CAUSAL,
  538.                 BLOCK_HEADDIM=BLOCK_HEADDIM,
  539.                 EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM,
  540.                 BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N
  541.             )
  542.     else:
  543.         start_n = tl.program_id(0)
  544.         _bwd_kernel_one_col_block(
  545.             start_n,
  546.             Q, K, V, Bias,
  547.             DO, DQ, DK, DV,
  548.             LSE, D,
  549.             softmax_scale,
  550.             stride_qm, stride_kn, stride_vn, stride_bm,
  551.             stride_dom, stride_dqm, stride_dkn, stride_dvn,
  552.             seqlen_q, seqlen_k, headdim,
  553.             ATOMIC_ADD=True,
  554.             BIAS_TYPE=BIAS_TYPE,
  555.             IS_CAUSAL=IS_CAUSAL,
  556.             BLOCK_HEADDIM=BLOCK_HEADDIM,
  557.             EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM,
  558.             BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N
  559.         )
  560.  
  561.  
  562. def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
  563.     # shape constraints
  564.     batch, seqlen_q, nheads, d = q.shape
  565.     _, seqlen_k, _, _ = k.shape
  566.     assert k.shape == (batch, seqlen_k, nheads, d)
  567.     assert v.shape == (batch, seqlen_k, nheads, d)
  568.     assert d <= 128, 'FlashAttention only support head dimensions up to 128'
  569.     assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
  570.     assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
  571.     assert q.is_cuda and k.is_cuda and v.is_cuda
  572.     softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
  573.  
  574.     has_bias = bias is not None
  575.     bias_type = 'none'
  576.     if has_bias:
  577.         assert bias.dtype in [q.dtype, torch.float]
  578.         assert bias.is_cuda
  579.         assert bias.dim() == 4
  580.         if bias.stride(-1) != 1:
  581.             bias = bias.contiguous()
  582.         if bias.shape[2:] == (1, seqlen_k):
  583.             bias_type = 'vector'
  584.         elif bias.shape[2:] == (seqlen_q, seqlen_k):
  585.             bias_type = 'matrix'
  586.         else:
  587.             raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
  588.                                ' or (seqlen_q, seqlen_k)')
  589.         bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
  590.     bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
  591.  
  592.     seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
  593.     lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
  594.     tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
  595.     o = torch.empty_like(q)
  596.  
  597.     BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
  598.     BLOCK = 128
  599.     num_warps = 4 if d <= 64 else 8
  600.     grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads)
  601.     _fwd_kernel[grid](
  602.         q, k, v, bias, o,
  603.         lse, tmp,
  604.         softmax_scale,
  605.         q.stride(0), q.stride(2), q.stride(1),
  606.         k.stride(0), k.stride(2), k.stride(1),
  607.         v.stride(0), v.stride(2), v.stride(1),
  608.         *bias_strides,
  609.         o.stride(0), o.stride(2), o.stride(1),
  610.         nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d,
  611.         seqlen_q // 32, seqlen_k // 32,  # key for triton cache (limit number of compilations)
  612.         # Can't use kwargs here because triton autotune expects key to be args, not kwargs
  613.         # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
  614.         bias_type, causal, BLOCK_HEADDIM,
  615.         BLOCK_M=BLOCK, BLOCK_N=BLOCK,
  616.         num_warps=num_warps,
  617.         num_stages=1,
  618.     )
  619.     return o, lse, softmax_scale  # softmax_scale could have been updated
  620.  
  621.  
  622. def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
  623.     # Make sure that the last dimension is contiguous
  624.     if do.stride(-1) != 1:
  625.         do = do.contiguous()
  626.     batch, seqlen_q, nheads, d = q.shape
  627.     _, seqlen_k, _, _ = k.shape
  628.     # assert d in {16, 32, 64, 128}
  629.     assert d <= 128
  630.     seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
  631.     assert lse.shape == (batch, nheads, seqlen_q_rounded)
  632.     assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
  633.     assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
  634.     softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
  635.     # dq_accum = torch.zeros_like(q, dtype=torch.float32)
  636.     dq_accum = torch.empty_like(q, dtype=torch.float32)
  637.     delta = torch.empty_like(lse)
  638.     # delta = torch.zeros_like(lse)
  639.  
  640.     BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
  641.     grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads)
  642.     _bwd_preprocess_do_o_dot[grid](
  643.         o, do, delta,
  644.         o.stride(0), o.stride(2), o.stride(1),
  645.         do.stride(0), do.stride(2), do.stride(1),
  646.         nheads, seqlen_q, seqlen_q_rounded, d,
  647.         BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM,
  648.     )
  649.  
  650.     has_bias = bias is not None
  651.     bias_type = 'none'
  652.     if has_bias:
  653.         assert bias.dtype in [q.dtype, torch.float]
  654.         assert bias.is_cuda
  655.         assert bias.dim() == 4
  656.         assert bias.stride(-1) == 1
  657.         if bias.shape[2:] == (1, seqlen_k):
  658.             bias_type = 'vector'
  659.         elif bias.shape[2:] == (seqlen_q, seqlen_k):
  660.             bias_type = 'matrix'
  661.         else:
  662.             raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k)'
  663.                                ' or (seqlen_q, seqlen_k)')
  664.         bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
  665.     bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
  666.  
  667.     # BLOCK_M = 128
  668.     # BLOCK_N = 64
  669.     # num_warps = 4
  670.     grid = lambda META: (triton.cdiv(seqlen_k, META["BLOCK_N"]) if META["SEQUENCE_PARALLEL"] else 1,
  671.                          batch * nheads)
  672.     _bwd_kernel[grid](
  673.         q, k, v, bias,
  674.         do, dq_accum, dk, dv,
  675.         lse, delta,
  676.         softmax_scale,
  677.         q.stride(0), q.stride(2), q.stride(1),
  678.         k.stride(0), k.stride(2), k.stride(1),
  679.         v.stride(0), v.stride(2), v.stride(1),
  680.         *bias_strides,
  681.         do.stride(0), do.stride(2), do.stride(1),
  682.         dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1),
  683.         dk.stride(0), dk.stride(2), dk.stride(1),
  684.         dv.stride(0), dv.stride(2), dv.stride(1),
  685.         nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d,
  686.         seqlen_q // 32, seqlen_k // 32,  # key for triton cache (limit number of compilations)
  687.         # Can't use kwargs here because triton autotune expects key to be args, not kwargs
  688.         # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
  689.         bias_type, causal, BLOCK_HEADDIM,
  690.         # SEQUENCE_PARALLEL=False,
  691.         # BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N,
  692.         # num_warps=num_warps,
  693.         # num_stages=1,
  694.     )
  695.     dq.copy_(dq_accum)
  696.  
  697.  
  698. class FlashAttnQKVPackedFunc(torch.autograd.Function):
  699.  
  700.     @staticmethod
  701.     def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
  702.         """
  703.            qkv: (batch, seqlen, 3, nheads, headdim)
  704.            bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
  705.                For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
  706.                ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
  707.        """
  708.         # Make sure that the last dimension is contiguous
  709.         if qkv.stride(-1) != 1:
  710.             qkv = qkv.contiguous()
  711.         o, lse, ctx.softmax_scale = _flash_attn_forward(
  712.             qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal,
  713.             softmax_scale=softmax_scale
  714.         )
  715.         ctx.save_for_backward(qkv, o, lse, bias)
  716.         ctx.causal = causal
  717.         return o
  718.  
  719.     @staticmethod
  720.     def backward(ctx, do):
  721.         qkv, o, lse, bias = ctx.saved_tensors
  722.         assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
  723.         # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
  724.         # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
  725.         with torch.inference_mode():
  726.             dqkv = torch.empty_like(qkv)
  727.             _flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse,
  728.                                  dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2],
  729.                                  bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
  730.         return dqkv, None, None, None
  731.  
  732.  
  733. flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
  734.  
  735.  
  736. class FlashAttnKVPackedFunc(torch.autograd.Function):
  737.  
  738.     @staticmethod
  739.     def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
  740.         """
  741.            q: (batch, seqlen_q, nheads, headdim)
  742.            kv: (batch, seqlen_k, 2, nheads, headdim)
  743.            bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
  744.                For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
  745.                ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
  746.        """
  747.         # Make sure that the last dimension is contiguous
  748.         q, kv = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
  749.         o, lse, ctx.softmax_scale = _flash_attn_forward(
  750.             q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale
  751.         )
  752.         ctx.save_for_backward(q, kv, o, lse, bias)
  753.         ctx.causal = causal
  754.         return o
  755.  
  756.     @staticmethod
  757.     def backward(ctx, do):
  758.         q, kv, o, lse, bias = ctx.saved_tensors
  759.         if len(ctx.needs_input_grad) >= 3:
  760.             assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
  761.         # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
  762.         # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
  763.         with torch.inference_mode():
  764.             dq = torch.empty_like(q)
  765.             dkv = torch.empty_like(kv)
  766.             _flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse,
  767.                                  dq, dkv[:, :, 0], dkv[:, :, 1],
  768.                                  bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
  769.         return dq, dkv, None, None, None
  770.  
  771.  
  772. flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
  773.  
  774.  
  775. class FlashAttnFunc(torch.autograd.Function):
  776.  
  777.     @staticmethod
  778.     def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
  779.         """
  780.            q: (batch_size, seqlen_q, nheads, headdim)
  781.            k, v: (batch_size, seqlen_k, nheads, headdim)
  782.            bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
  783.                For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
  784.                ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
  785.        """
  786.         # Make sure that the last dimension is contiguous
  787.         q, k, v = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
  788.         o, lse, ctx.softmax_scale = _flash_attn_forward(
  789.             q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale
  790.         )
  791.         ctx.save_for_backward(q, k, v, o, lse, bias)
  792.         ctx.causal = causal
  793.         return o
  794.  
  795.     @staticmethod
  796.     def backward(ctx, do):
  797.         q, k, v, o, lse, bias = ctx.saved_tensors
  798.         assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
  799.         # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
  800.         # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
  801.         with torch.inference_mode():
  802.             dq = torch.empty_like(q)
  803.             dk = torch.empty_like(k)
  804.             dv = torch.empty_like(v)
  805.             _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv,
  806.                                  bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
  807.         return dq, dk, dv, None, None, None
  808.  
  809.  
  810. flash_attn_func = FlashAttnFunc.apply
  811.  
  812.  
  813. def triton_flash_attn_fn(
  814.         query: torch.Tensor,
  815.         key: torch.Tensor,
  816.         value: torch.Tensor,
  817.         n_heads: int,
  818.         softmax_scale: Optional[float] = None,
  819.         attn_bias: Optional[torch.Tensor] = None,
  820.         is_causal: bool = False,
  821.         multiquery: bool = False,
  822. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor,
  823. torch.Tensor]]]:
  824.     """Flash attention with Triton backend."""
  825.     query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
  826.     key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
  827.     value = rearrange(value,
  828.                       'b s (h d) -> b s h d',
  829.                       h=1 if multiquery else n_heads)
  830.  
  831.     attn_output = flash_attn_func(  # type: ignore
  832.         query, key, value, attn_bias, is_causal, softmax_scale)
  833.  
  834.     output = attn_output.view(*attn_output.shape[:2], -1)  # type: ignore
  835.  
  836.     return output
  837.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement