flash_api.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. /******************************************************************************
  2. * Copyright (c) 2024, Tri Dao.
  3. ******************************************************************************/
  4. // Include these 2 headers instead of torch/extension.h since we don't need all of the torch headers.
  5. #include <torch/python.h>
  6. #include <torch/nn/functional.h>
  7. #include <c10/cuda/CUDAGuard.h>
  8. #include <c10/cuda/CUDAStream.h>
  9. #include <ATen/cuda/CUDAGeneratorImpl.h> // For at::Generator and at::PhiloxCudaState
  10. #include "philox_unpack.cuh" // For at::cuda::philox::unpack
  11. #include <cutlass/numeric_types.h>
  12. #include "hardware_info.h"
  13. #include "flash.h"
  14. #include "static_switch.h"
  15. #define CHECK_DEVICE(x) TORCH_CHECK(x.is_cuda(), #x " must be on CUDA")
  16. #define CHECK_SHAPE(x, ...) TORCH_CHECK(x.sizes() == torch::IntArrayRef({__VA_ARGS__}), #x " must have shape (" #__VA_ARGS__ ")")
  17. #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
  18. void set_params_fprop(Flash_fwd_params &params,
  19. // sizes
  20. const size_t b,
  21. const size_t seqlen_q,
  22. const size_t seqlen_k,
  23. const size_t seqlen_q_rounded,
  24. const size_t seqlen_k_rounded,
  25. const size_t h,
  26. const size_t h_k,
  27. const size_t d,
  28. const size_t d_rounded,
  29. // device pointers
  30. const at::Tensor q,
  31. const at::Tensor k,
  32. const at::Tensor v,
  33. at::Tensor out,
  34. void *cu_seqlens_q_d,
  35. void *cu_seqlens_k_d,
  36. void *seqused_k,
  37. void *p_d,
  38. void *softmax_lse_d,
  39. float p_dropout,
  40. float softmax_scale,
  41. int window_size_left,
  42. int window_size_right,
  43. const float softcap,
  44. bool seqlenq_ngroups_swapped=false,
  45. const bool unpadded_lse=false) {
  46. // Reset the parameters
  47. params = {};
  48. params.is_bf16 = q.dtype() == torch::kBFloat16;
  49. // Set the pointers and strides.
  50. params.q_ptr = q.data_ptr();
  51. params.k_ptr = k.data_ptr();
  52. params.v_ptr = v.data_ptr();
  53. // All stride are in elements, not bytes.
  54. params.q_row_stride = q.stride(-3);
  55. params.k_row_stride = k.stride(-3);
  56. params.v_row_stride = v.stride(-3);
  57. params.q_head_stride = q.stride(-2);
  58. params.k_head_stride = k.stride(-2);
  59. params.v_head_stride = v.stride(-2);
  60. params.o_ptr = out.data_ptr();
  61. params.o_row_stride = out.stride(-3);
  62. params.o_head_stride = out.stride(-2);
  63. if (cu_seqlens_q_d == nullptr) {
  64. params.q_batch_stride = q.stride(0);
  65. params.k_batch_stride = k.stride(0);
  66. params.v_batch_stride = v.stride(0);
  67. params.o_batch_stride = out.stride(0);
  68. if (seqlenq_ngroups_swapped) {
  69. params.q_batch_stride *= seqlen_q;
  70. params.o_batch_stride *= seqlen_q;
  71. }
  72. }
  73. params.cu_seqlens_q = static_cast<int *>(cu_seqlens_q_d);
  74. params.cu_seqlens_k = static_cast<int *>(cu_seqlens_k_d);
  75. params.seqused_k = static_cast<int *>(seqused_k);
  76. // P = softmax(QK^T)
  77. params.p_ptr = p_d;
  78. // Softmax sum
  79. params.softmax_lse_ptr = softmax_lse_d;
  80. // Set the dimensions.
  81. params.b = b;
  82. params.h = h;
  83. params.h_k = h_k;
  84. params.h_h_k_ratio = h / h_k;
  85. params.seqlen_q = seqlen_q;
  86. params.seqlen_k = seqlen_k;
  87. params.seqlen_q_rounded = seqlen_q_rounded;
  88. params.seqlen_k_rounded = seqlen_k_rounded;
  89. params.d = d;
  90. params.d_rounded = d_rounded;
  91. // Set the different scale values.
  92. #ifdef FLASHATTENTION_DISABLE_SOFTCAP
  93. TORCH_CHECK(softcap <= 0.0, "This flash attention build does not support softcap.");
  94. #endif
  95. if (softcap > 0.0) {
  96. params.softcap = softmax_scale / softcap;
  97. params.scale_softmax = softcap;
  98. params.scale_softmax_log2 = softcap * M_LOG2E;
  99. } else{
  100. // Remove potential NaN
  101. params.softcap = 0.0;
  102. params.scale_softmax = softmax_scale;
  103. params.scale_softmax_log2 = softmax_scale * M_LOG2E;
  104. }
  105. // Set this to probability of keeping an element to simplify things.
  106. params.p_dropout = 1.f - p_dropout;
  107. // Convert p from float to int so we don't have to convert the random uint to float to compare.
  108. // [Minor] We want to round down since when we do the comparison we use <= instead of <
  109. // params.p_dropout_in_uint = uint32_t(std::floor(params.p_dropout * 4294967295.0));
  110. // params.p_dropout_in_uint16_t = uint16_t(std::floor(params.p_dropout * 65535.0));
  111. params.p_dropout_in_uint8_t = uint8_t(std::floor(params.p_dropout * 255.0));
  112. params.rp_dropout = 1.f / params.p_dropout;
  113. params.scale_softmax_rp_dropout = params.rp_dropout * params.scale_softmax;
  114. TORCH_CHECK(p_dropout < 1.f);
  115. #ifdef FLASHATTENTION_DISABLE_DROPOUT
  116. TORCH_CHECK(p_dropout == 0.0f, "This flash attention build does not support dropout.");
  117. #endif
  118. // Causal is the special case where window_size_right == 0 and window_size_left < 0.
  119. // Local is the more general case where window_size_right >= 0 or window_size_left >= 0.
  120. params.is_causal = window_size_left < 0 && window_size_right == 0;
  121. if (window_size_left < 0 && window_size_right >= 0) { window_size_left = seqlen_k; }
  122. if (window_size_left >= 0 && window_size_right < 0) { window_size_right = seqlen_k; }
  123. params.window_size_left = window_size_left;
  124. params.window_size_right = window_size_right;
  125. #ifdef FLASHATTENTION_DISABLE_LOCAL
  126. TORCH_CHECK(params.is_causal || (window_size_left < 0 && window_size_right < 0),
  127. "This flash attention build does not support local attention.");
  128. #endif
  129. params.is_seqlens_k_cumulative = true;
  130. #ifdef FLASHATTENTION_DISABLE_UNEVEN_K
  131. TORCH_CHECK(d == d_rounded, "This flash attention build does not support headdim not being a multiple of 32.");
  132. #endif
  133. params.unpadded_lse = unpadded_lse;
  134. params.seqlenq_ngroups_swapped = seqlenq_ngroups_swapped;
  135. }
  136. void set_params_dgrad(Flash_bwd_params &params,
  137. // sizes
  138. const size_t b,
  139. const size_t seqlen_q,
  140. const size_t seqlen_k,
  141. const size_t seqlen_q_rounded,
  142. const size_t seqlen_k_rounded,
  143. const size_t h,
  144. const size_t h_k,
  145. const size_t d,
  146. const size_t d_rounded,
  147. // device pointers
  148. const at::Tensor q,
  149. const at::Tensor k,
  150. const at::Tensor v,
  151. const at::Tensor out,
  152. const at::Tensor dout,
  153. at::Tensor dq,
  154. at::Tensor dk,
  155. at::Tensor dv,
  156. void *cu_seqlens_q_d,
  157. void *cu_seqlens_k_d,
  158. void *dq_accum_d,
  159. void *dk_accum_d,
  160. void *dv_accum_d,
  161. void *softmax_lse_d,
  162. void *dsoftmax_sum_d,
  163. float p_dropout,
  164. float softmax_scale,
  165. int window_size_left,
  166. int window_size_right,
  167. const float softcap,
  168. bool deterministic,
  169. const bool unpadded_lse) {
  170. set_params_fprop(params,
  171. b, seqlen_q, seqlen_k, seqlen_q_rounded, seqlen_k_rounded, h, h_k, d, d_rounded,
  172. q, k, v, out,
  173. cu_seqlens_q_d,
  174. cu_seqlens_k_d,
  175. nullptr,
  176. nullptr,
  177. softmax_lse_d,
  178. p_dropout,
  179. softmax_scale,
  180. window_size_left,
  181. window_size_right,
  182. softcap,
  183. false, // seqlenq_ngroups_swapped
  184. unpadded_lse);
  185. // Set the pointers and strides.
  186. params.do_ptr = dout.data_ptr();
  187. params.do_row_stride = dout.stride(-3);
  188. params.do_head_stride = dout.stride(-2);
  189. params.dq_ptr = dq.data_ptr();
  190. params.dk_ptr = dk.data_ptr();
  191. params.dv_ptr = dv.data_ptr();
  192. params.dq_row_stride = dq.stride(-3);
  193. params.dk_row_stride = dk.stride(-3);
  194. params.dv_row_stride = dv.stride(-3);
  195. params.dq_head_stride = dq.stride(-2);
  196. params.dk_head_stride = dk.stride(-2);
  197. params.dv_head_stride = dv.stride(-2);
  198. if (cu_seqlens_q_d == nullptr) {
  199. params.do_batch_stride = dout.stride(0);
  200. params.dq_batch_stride = dq.stride(0);
  201. params.dk_batch_stride = dk.stride(0);
  202. params.dv_batch_stride = dv.stride(0);
  203. }
  204. params.dq_accum_ptr = dq_accum_d;
  205. params.dk_accum_ptr = dk_accum_d;
  206. params.dv_accum_ptr = dv_accum_d;
  207. // Softmax sum
  208. params.dsoftmax_sum = dsoftmax_sum_d;
  209. params.deterministic = deterministic;
  210. }
  211. void run_mha_fwd(Flash_fwd_params &params, cudaStream_t stream, bool force_split_kernel=false) {
  212. FP16_SWITCH(!params.is_bf16, [&] {
  213. HEADDIM_SWITCH(params.d, [&] {
  214. BOOL_SWITCH(params.is_causal, Is_causal, [&] {
  215. if (params.num_splits <= 1 && !force_split_kernel) { // If we don't set it num_splits == 0
  216. run_mha_fwd_<elem_type, kHeadDim, Is_causal>(params, stream);
  217. } else {
  218. run_mha_fwd_splitkv_dispatch<elem_type, kHeadDim, Is_causal>(params, stream);
  219. }
  220. });
  221. });
  222. });
  223. }
  224. // Find the number of splits that maximizes the occupancy. For example, if we have
  225. // batch * n_heads = 48 and we have 108 SMs, having 2 splits (efficiency = 0.89) is
  226. // better than having 3 splits (efficiency = 0.67). However, we also don't want too many
  227. // splits as that would incur more HBM reads/writes.
  228. // So we find the best efficiency, then find the smallest number of splits that gets 85%
  229. // of the best efficiency.
  230. inline int num_splits_heuristic(int batch_nheads_mblocks, int num_SMs, int num_n_blocks, int max_splits) {
  231. // If we have enough to almost fill the SMs, then just use 1 split
  232. if (batch_nheads_mblocks >= 0.8f * num_SMs) { return 1; }
  233. max_splits = std::min({max_splits, num_SMs, num_n_blocks});
  234. float max_efficiency = 0.f;
  235. std::vector<float> efficiency;
  236. efficiency.reserve(max_splits);
  237. auto ceildiv = [](int a, int b) { return (a + b - 1) / b; };
  238. // Some splits are not eligible. For example, if we have 64 blocks and choose 11 splits,
  239. // we'll have 6 * 10 + 4 blocks. If we choose 12 splits, we'll have 6 * 11 + (-2) blocks
  240. // (i.e. it's 11 splits anyway).
  241. // So we check if the number of blocks per split is the same as the previous num_splits.
  242. auto is_split_eligible = [&ceildiv, &num_n_blocks](int num_splits) {
  243. return num_splits == 1 || ceildiv(num_n_blocks, num_splits) != ceildiv(num_n_blocks, num_splits - 1);
  244. };
  245. for (int num_splits = 1; num_splits <= max_splits; num_splits++) {
  246. if (!is_split_eligible(num_splits)) {
  247. efficiency.push_back(0.f);
  248. } else {
  249. float n_waves = float(batch_nheads_mblocks * num_splits) / num_SMs;
  250. float eff = n_waves / ceil(n_waves);
  251. // printf("num_splits = %d, eff = %f\n", num_splits, eff);
  252. if (eff > max_efficiency) { max_efficiency = eff; }
  253. efficiency.push_back(eff);
  254. }
  255. }
  256. for (int num_splits = 1; num_splits <= max_splits; num_splits++) {
  257. if (!is_split_eligible(num_splits)) { continue; }
  258. if (efficiency[num_splits - 1] >= 0.85 * max_efficiency) {
  259. // printf("num_splits chosen = %d\n", num_splits);
  260. return num_splits;
  261. }
  262. }
  263. return 1;
  264. }
  265. std::tuple<at::Tensor, at::Tensor> set_params_splitkv(Flash_fwd_params &params, const int batch_size,
  266. const int num_heads, const int head_size, const int max_seqlen_k, const int max_seqlen_q,
  267. const int head_size_rounded, const float p_dropout,
  268. const int num_splits, const int num_sm, struct c10::TensorOptions opts) {
  269. // This needs to match with run_mha_fwd_splitkv_dispatch
  270. const int block_n = head_size <= 64 ? 256 : (head_size <= 128 ? 128 : 64);
  271. const int num_n_blocks = (max_seqlen_k + block_n - 1) / block_n;
  272. // Technically kBlockM = 64 only for the splitKV kernels, not the standard kernel.
  273. // In any case we don't expect seqlen_q to be larger than 64 for inference.
  274. const int num_m_blocks = (max_seqlen_q + 64 - 1) / 64;
  275. params.num_splits = num_splits;
  276. at::Tensor softmax_lse_accum;
  277. at::Tensor out_accum;
  278. if (p_dropout == 0.0f) { // SplitKV is not implemented for dropout
  279. if (num_splits < 1) {
  280. // We multiply number of SMs by 2 to hard-code the fact that we're using 128 threads per block.
  281. params.num_splits = num_splits_heuristic(batch_size * num_heads * num_m_blocks, num_sm * 2, num_n_blocks, 128);
  282. }
  283. if (params.num_splits > 1) {
  284. softmax_lse_accum = torch::empty({params.num_splits, batch_size, num_heads, max_seqlen_q}, opts.dtype(at::kFloat));
  285. out_accum = torch::empty({params.num_splits, batch_size, num_heads, max_seqlen_q, head_size_rounded}, opts.dtype(at::kFloat));
  286. params.softmax_lseaccum_ptr = softmax_lse_accum.data_ptr();
  287. params.oaccum_ptr = out_accum.data_ptr();
  288. }
  289. TORCH_CHECK(params.num_splits <= 128, "num_splits > 128 not supported");
  290. }
  291. return std::make_tuple(softmax_lse_accum, out_accum);
  292. }
  293. void set_params_alibi(Flash_fwd_params &params, c10::optional<at::Tensor> &alibi_slopes_, int batch_size, int num_heads){
  294. #ifdef FLASHATTENTION_DISABLE_ALIBI
  295. TORCH_CHECK(!alibi_slopes_.has_value(), "This flash attention build does not support alibi.");
  296. params.alibi_slopes_ptr = nullptr;
  297. #else
  298. if (alibi_slopes_.has_value()) {
  299. auto alibi_slopes = alibi_slopes_.value();
  300. TORCH_CHECK(alibi_slopes.dtype() == torch::kFloat32, "ALiBi slopes must have dtype fp32");
  301. CHECK_DEVICE(alibi_slopes);
  302. TORCH_CHECK(alibi_slopes.stride(-1) == 1, "ALiBi slopes tensor must have contiguous last dimension");
  303. TORCH_CHECK(alibi_slopes.sizes() == torch::IntArrayRef({num_heads}) || alibi_slopes.sizes() == torch::IntArrayRef({batch_size, num_heads}));
  304. params.alibi_slopes_ptr = alibi_slopes.data_ptr();
  305. params.alibi_slopes_batch_stride = alibi_slopes.dim() == 2 ? alibi_slopes.stride(0) : 0;
  306. } else {
  307. params.alibi_slopes_ptr = nullptr;
  308. }
  309. #endif
  310. }
  311. std::vector<at::Tensor>
  312. mha_fwd(at::Tensor &q, // batch_size x seqlen_q x num_heads x round_multiple(head_size, 8)
  313. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x round_multiple(head_size, 8)
  314. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x round_multiple(head_size, 8)
  315. c10::optional<at::Tensor> &out_, // batch_size x seqlen_q x num_heads x round_multiple(head_size, 8)
  316. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
  317. const float p_dropout,
  318. const float softmax_scale,
  319. bool is_causal,
  320. int window_size_left,
  321. int window_size_right,
  322. const float softcap,
  323. const bool return_softmax,
  324. c10::optional<at::Generator> gen_) {
  325. // Otherwise the kernel will be launched from cuda:0 device
  326. at::cuda::CUDAGuard device_guard{q.device()};
  327. auto [cc_major, cc_minor] = get_compute_capability(get_current_device());
  328. // bool is_sm75 = cc_major == 7 && cc_minor == 5;
  329. bool is_sm8x = cc_major == 8 && cc_minor >= 0;
  330. bool is_sm90 = cc_major == 9 && cc_minor == 0;
  331. TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
  332. // We will support Turing in the near future
  333. // TORCH_CHECK(is_sm90 || is_sm8x || is_sm75, "FlashAttention only supports Turing GPUs or newer.");
  334. auto q_dtype = q.dtype();
  335. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  336. "FlashAttention only support fp16 and bf16 data type");
  337. if (q_dtype == torch::kBFloat16) {
  338. TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
  339. }
  340. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  341. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  342. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  343. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  344. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  345. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  346. const auto sizes = q.sizes();
  347. const int batch_size = sizes[0];
  348. int seqlen_q = sizes[1];
  349. int num_heads = sizes[2];
  350. const int head_size = sizes[3];
  351. const int seqlen_k = k.size(1);
  352. const int num_heads_k = k.size(2);
  353. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  354. TORCH_CHECK(head_size <= 256, "FlashAttention forward only supports head dimension at most 256");
  355. TORCH_CHECK(head_size % 8 == 0, "query, key, value, and out_ must have a head_size that is a multiple of 8");
  356. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  357. if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }
  358. if (window_size_left >= seqlen_k) { window_size_left = -1; }
  359. if (window_size_right >= seqlen_k) { window_size_right = -1; }
  360. // causal=true is the same as causal=false in this case
  361. if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }
  362. if (is_causal) { window_size_right = 0; }
  363. // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
  364. // H/t Daniel Haziza
  365. const int seqlenq_ngroups_swapped = seqlen_q == 1 && num_heads > num_heads_k && window_size_left < 0 && window_size_right < 0 && p_dropout == 0.f && head_size % 8 == 0 && !alibi_slopes_.has_value();
  366. const int ngroups = num_heads / num_heads_k;
  367. if (seqlenq_ngroups_swapped) {
  368. q = q.reshape({batch_size, num_heads_k, ngroups, head_size}).transpose(1, 2);
  369. seqlen_q = ngroups;
  370. num_heads = num_heads_k;
  371. }
  372. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size);
  373. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size);
  374. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size);
  375. at::Tensor out;
  376. if (out_.has_value()) {
  377. out = out_.value();
  378. TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  379. CHECK_DEVICE(out);
  380. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  381. CHECK_SHAPE(out, batch_size, sizes[1], sizes[2], head_size);
  382. if (seqlenq_ngroups_swapped) {
  383. out = out.reshape({batch_size, num_heads_k, ngroups, head_size}).transpose(1, 2);
  384. }
  385. } else {
  386. out = torch::empty_like(q);
  387. }
  388. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  389. const int head_size_rounded = head_size <= 192 ? round_multiple(head_size, 32) : 256;
  390. const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
  391. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  392. auto opts = q.options();
  393. auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  394. at::Tensor p;
  395. // Only return softmax if there's dropout to reduce compilation time
  396. if (return_softmax) {
  397. TORCH_CHECK(p_dropout > 0.0f, "return_softmax is only supported when p_dropout > 0.0");
  398. p = torch::empty({ batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded }, opts);
  399. }
  400. else {
  401. p = torch::empty({ 0 }, opts);
  402. }
  403. Flash_fwd_params params;
  404. set_params_fprop(params,
  405. batch_size,
  406. seqlen_q, seqlen_k,
  407. seqlen_q_rounded, seqlen_k_rounded,
  408. num_heads, num_heads_k,
  409. head_size, head_size_rounded,
  410. q, k, v, out,
  411. /*cu_seqlens_q_d=*/nullptr,
  412. /*cu_seqlens_k_d=*/nullptr,
  413. /*seqused_k=*/nullptr,
  414. return_softmax ? p.data_ptr() : nullptr,
  415. softmax_lse.data_ptr(),
  416. p_dropout,
  417. softmax_scale,
  418. window_size_left,
  419. window_size_right,
  420. softcap
  421. );
  422. // Keep references to these tensors to extend their lifetime
  423. at::Tensor softmax_lse_accum, out_accum;
  424. std::tie(softmax_lse_accum, out_accum) = set_params_splitkv(
  425. params, batch_size, num_heads, head_size, seqlen_k, seqlen_q,
  426. head_size_rounded, p_dropout, /*num_splits*/ 0, get_num_sm(get_current_device()), opts);
  427. // number of times random will be generated per thread, to offset philox counter in thc random
  428. // state
  429. // We use a custom RNG that increases the offset by batch_size * nheads * 32.
  430. int64_t counter_offset = params.b * params.h * 32;
  431. auto options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA);
  432. auto rng_state = torch::empty({2}, options.dtype(torch::kInt64));
  433. // Forward kernel will populate memory with the seed and offset.
  434. params.rng_state = reinterpret_cast<uint64_t*>(rng_state.data_ptr());
  435. if (p_dropout > 0.0) {
  436. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  437. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  438. // See Note [Acquire lock when using random generators]
  439. std::lock_guard<std::mutex> lock(gen->mutex_);
  440. params.philox_args = gen->philox_cuda_state(counter_offset);
  441. }
  442. set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
  443. if (seqlen_k > 0) {
  444. auto stream = at::cuda::getCurrentCUDAStream().stream();
  445. run_mha_fwd(params, stream);
  446. } else {
  447. // If seqlen_k == 0, then we have an empty tensor. We need to set the output to 0.
  448. out.zero_();
  449. softmax_lse.fill_(std::numeric_limits<float>::infinity());
  450. }
  451. if (seqlenq_ngroups_swapped) {
  452. out = out.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size});
  453. q = q.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size});
  454. softmax_lse = softmax_lse.reshape({batch_size, num_heads_k * seqlen_q, 1});
  455. }
  456. return {out, softmax_lse, p, rng_state};
  457. }
  458. std::vector<at::Tensor>
  459. mha_varlen_fwd(at::Tensor &q, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
  460. const at::Tensor &k, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i or num_blocks x page_block_size x num_heads_k x head_size if there's a block_table.
  461. const at::Tensor &v, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i or num_blocks x page_block_size x num_heads_k x head_size if there's a block_table.
  462. c10::optional<at::Tensor> &out_, // total_q x num_heads x head_size, total_k := \sum_{i=0}^{b} s_i
  463. const at::Tensor &cu_seqlens_q, // b+1
  464. const at::Tensor &cu_seqlens_k, // b+1
  465. c10::optional<at::Tensor> &seqused_k, // b. If given, only this many elements of each batch element's keys are used.
  466. c10::optional<const at::Tensor> &leftpad_k_, // batch_size
  467. c10::optional<at::Tensor> &block_table_, // batch_size x max_num_blocks_per_seq
  468. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or b x num_heads
  469. int max_seqlen_q,
  470. const int max_seqlen_k,
  471. const float p_dropout,
  472. const float softmax_scale,
  473. const bool zero_tensors,
  474. bool is_causal,
  475. int window_size_left,
  476. int window_size_right,
  477. const float softcap,
  478. const bool return_softmax,
  479. c10::optional<at::Generator> gen_) {
  480. // Otherwise the kernel will be launched from cuda:0 device
  481. at::cuda::CUDAGuard device_guard{q.device()};
  482. auto [cc_major, cc_minor] = get_compute_capability(get_current_device());
  483. // bool is_sm75 = cc_major == 7 && cc_minor == 5;
  484. bool is_sm8x = cc_major == 8 && cc_minor >= 0;
  485. bool is_sm90 = cc_major == 9 && cc_minor == 0;
  486. TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
  487. // We will support Turing in the near future
  488. // TORCH_CHECK(is_sm90 || is_sm8x || is_sm75, "FlashAttention only supports Turing GPUs or newer.");
  489. auto q_dtype = q.dtype();
  490. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  491. "FlashAttention only support fp16 and bf16 data type");
  492. if (q_dtype == torch::kBFloat16) {
  493. TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
  494. }
  495. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  496. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  497. TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
  498. TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");
  499. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  500. CHECK_DEVICE(cu_seqlens_q);
  501. CHECK_DEVICE(cu_seqlens_k);
  502. at::Tensor block_table;
  503. const bool paged_KV = block_table_.has_value();
  504. if (paged_KV) {
  505. block_table = block_table_.value();
  506. CHECK_DEVICE(block_table);
  507. TORCH_CHECK(block_table.dtype() == torch::kInt32, "block_table must have dtype torch.int32");
  508. TORCH_CHECK(block_table.stride(-1) == 1, "block_table must have contiguous last dimension");
  509. }
  510. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  511. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  512. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  513. CHECK_CONTIGUOUS(cu_seqlens_q);
  514. CHECK_CONTIGUOUS(cu_seqlens_k);
  515. const auto sizes = q.sizes();
  516. const int batch_size = cu_seqlens_q.numel() - 1;
  517. int num_heads = sizes[1];
  518. const int head_size = sizes[2];
  519. const int num_heads_k = paged_KV ? k.size(2) : k.size(1);
  520. if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }
  521. const int max_num_blocks_per_seq = !paged_KV ? 0 : block_table.size(1);
  522. const int num_blocks = !paged_KV ? 0 : k.size(0);
  523. const int page_block_size = !paged_KV ? 1 : k.size(1);
  524. TORCH_CHECK(!paged_KV || page_block_size % 256 == 0, "Paged KV cache block size must be divisible by 256");
  525. if (max_seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; } // causal=true is the same as causal=false in this case
  526. if (is_causal) { window_size_right = 0; }
  527. void *cu_seqlens_q_d = cu_seqlens_q.data_ptr();
  528. // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
  529. // H/t Daniel Haziza
  530. const int seqlenq_ngroups_swapped = max_seqlen_q == 1 && num_heads > num_heads_k && window_size_left < 0 && window_size_right < 0 && p_dropout == 0.f && head_size % 8 == 0 && !alibi_slopes_.has_value();
  531. const int ngroups = num_heads / num_heads_k;
  532. if (seqlenq_ngroups_swapped) {
  533. q = q.reshape({batch_size, num_heads_k, ngroups, head_size}).transpose(1, 2).reshape({batch_size * ngroups, num_heads_k, head_size});
  534. max_seqlen_q = ngroups;
  535. num_heads = num_heads_k;
  536. cu_seqlens_q_d = nullptr;
  537. }
  538. const int total_q = q.sizes()[0];
  539. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  540. TORCH_CHECK(head_size <= 256, "FlashAttention forward only supports head dimension at most 256");
  541. TORCH_CHECK(head_size % 8 == 0, "query, key, value, and out_ must have a head_size that is a multiple of 8");
  542. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  543. if (window_size_left >= max_seqlen_k) { window_size_left = -1; }
  544. if (window_size_right >= max_seqlen_k) { window_size_right = -1; }
  545. CHECK_SHAPE(q, total_q, num_heads, head_size);
  546. if (!paged_KV) {
  547. const int total_k = k.size(0);
  548. CHECK_SHAPE(k, total_k, num_heads_k, head_size);
  549. CHECK_SHAPE(v, total_k, num_heads_k, head_size);
  550. } else {
  551. CHECK_SHAPE(k, num_blocks, page_block_size, num_heads_k, head_size);
  552. CHECK_SHAPE(v, num_blocks, page_block_size, num_heads_k, head_size);
  553. CHECK_SHAPE(block_table, batch_size, max_num_blocks_per_seq);
  554. }
  555. CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
  556. CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
  557. if (seqused_k.has_value()){
  558. auto seqused_k_ = seqused_k.value();
  559. TORCH_CHECK(seqused_k_.dtype() == torch::kInt32, "seqused_k must have dtype int32");
  560. TORCH_CHECK(seqused_k_.is_cuda(), "seqused_k must be on CUDA device");
  561. TORCH_CHECK(seqused_k_.is_contiguous(), "seqused_k must be contiguous");
  562. CHECK_SHAPE(seqused_k_, batch_size);
  563. }
  564. at::Tensor out;
  565. if (out_.has_value()) {
  566. out = out_.value();
  567. TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  568. CHECK_DEVICE(out);
  569. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  570. CHECK_SHAPE(out, sizes[0], sizes[1], head_size);
  571. if (seqlenq_ngroups_swapped) {
  572. out = out.reshape({batch_size, num_heads_k, ngroups, head_size}).transpose(1, 2).reshape({batch_size * ngroups, num_heads_k, head_size});
  573. }
  574. } else {
  575. out = torch::empty_like(q);
  576. }
  577. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  578. const int head_size_rounded = head_size <= 192 ? round_multiple(head_size, 32) : 256;
  579. const int seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
  580. const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
  581. auto opts = q.options();
  582. auto softmax_lse = torch::empty({num_heads, total_q}, opts.dtype(at::kFloat));
  583. at::Tensor p;
  584. // Only return softmax if there's dropout to reduce compilation time
  585. if (return_softmax) {
  586. TORCH_CHECK(p_dropout > 0.0f, "return_softmax is only supported when p_dropout > 0.0");
  587. p = torch::empty({ batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded }, opts);
  588. }
  589. else {
  590. p = torch::empty({ 0 }, opts);
  591. }
  592. if (zero_tensors) {
  593. out.zero_();
  594. softmax_lse.fill_(-std::numeric_limits<float>::infinity());
  595. if (return_softmax) {p.zero_();}
  596. }
  597. Flash_fwd_params params;
  598. set_params_fprop(params,
  599. batch_size,
  600. max_seqlen_q, max_seqlen_k,
  601. seqlen_q_rounded, seqlen_k_rounded,
  602. num_heads, num_heads_k,
  603. head_size, head_size_rounded,
  604. q, k, v, out,
  605. cu_seqlens_q_d,
  606. cu_seqlens_k.data_ptr(),
  607. seqused_k.has_value() ? seqused_k.value().data_ptr() : nullptr,
  608. return_softmax ? p.data_ptr() : nullptr,
  609. softmax_lse.data_ptr(),
  610. p_dropout,
  611. softmax_scale,
  612. window_size_left,
  613. window_size_right,
  614. softcap,
  615. seqlenq_ngroups_swapped,
  616. /*unpadded_lse*/true);
  617. params.total_q = total_q;
  618. if (paged_KV) {
  619. params.block_table = block_table.data_ptr<int>();
  620. params.block_table_batch_stride = block_table.stride(0);
  621. params.k_batch_stride = k.stride(0);
  622. params.v_batch_stride = v.stride(0);
  623. }
  624. params.page_block_size = page_block_size;
  625. // Keep references to these tensors to extend their lifetime
  626. at::Tensor softmax_lse_accum, out_accum;
  627. if (seqlenq_ngroups_swapped) {
  628. // Only apply split-k for decoding
  629. std::tie(softmax_lse_accum, out_accum) =
  630. set_params_splitkv(params, batch_size, num_heads, head_size,
  631. max_seqlen_k, max_seqlen_q, head_size_rounded,
  632. p_dropout, /*num_splits*/ 0, get_num_sm(get_current_device()), opts);
  633. }
  634. if (leftpad_k_.has_value()) {
  635. auto leftpad_k = leftpad_k_.value();
  636. TORCH_CHECK(!paged_KV, "We don't support Paged KV and leftpad_k running at the same time yet");
  637. TORCH_CHECK(leftpad_k.dtype() == torch::kInt32, "leftpad_k must have dtype int32");
  638. CHECK_DEVICE(leftpad_k);
  639. CHECK_CONTIGUOUS(leftpad_k);
  640. CHECK_SHAPE(leftpad_k, batch_size);
  641. params.leftpad_k = static_cast<int *>(leftpad_k.data_ptr());
  642. }
  643. // number of times random will be generated per thread, to offset philox counter in thc random
  644. // state
  645. // We use a custom RNG that increases the offset by batch_size * nheads * 32.
  646. int64_t counter_offset = params.b * params.h * 32;
  647. auto options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA);
  648. auto rng_state = torch::empty({2}, options.dtype(torch::kInt64));
  649. // Forward kernel will populate memory with the seed and offset.
  650. params.rng_state = reinterpret_cast<uint64_t*>(rng_state.data_ptr());
  651. if (p_dropout > 0.0) {
  652. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  653. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  654. // See Note [Acquire lock when using random generators]
  655. std::lock_guard<std::mutex> lock(gen->mutex_);
  656. params.philox_args = gen->philox_cuda_state(counter_offset);
  657. }
  658. set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
  659. if (max_seqlen_k > 0) {
  660. auto stream = at::cuda::getCurrentCUDAStream().stream();
  661. run_mha_fwd(params, stream, paged_KV);
  662. } else {
  663. // If seqlen_k == 0, then we have an empty tensor. We need to set the output to 0.
  664. out.zero_();
  665. softmax_lse.fill_(std::numeric_limits<float>::infinity());
  666. }
  667. if (seqlenq_ngroups_swapped) {
  668. int64_t size_before[] = {batch_size, max_seqlen_q, num_heads_k, head_size};
  669. int64_t size_after[] = {batch_size, num_heads_k * max_seqlen_q, head_size};
  670. out = out.reshape(size_before).transpose(1, 2).reshape(size_after);
  671. q = q.reshape(size_before).transpose(1, 2).reshape(size_after);
  672. softmax_lse = softmax_lse.reshape({num_heads * max_seqlen_q, batch_size});
  673. }
  674. return {out, softmax_lse, p, rng_state};
  675. }
  676. void run_mha_bwd(Flash_bwd_params &params, cudaStream_t stream) {
  677. FP16_SWITCH(!params.is_bf16, [&] {
  678. HEADDIM_SWITCH(params.d, [&] {
  679. BOOL_SWITCH(params.is_causal, Is_causal, [&] {
  680. run_mha_bwd_<elem_type, kHeadDim, Is_causal>(params, stream);
  681. });
  682. });
  683. });
  684. }
  685. std::vector<at::Tensor>
  686. mha_bwd(const at::Tensor &dout, // batch_size x seqlen_q x num_heads, x multiple_of(head_size_og, 8)
  687. const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  688. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  689. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  690. const at::Tensor &out, // batch_size x seqlen_q x num_heads x head_size
  691. const at::Tensor &softmax_lse, // b x h x seqlen_q
  692. c10::optional<at::Tensor> &dq_, // batch_size x seqlen_q x num_heads x head_size
  693. c10::optional<at::Tensor> &dk_, // batch_size x seqlen_k x num_heads_k x head_size
  694. c10::optional<at::Tensor> &dv_, // batch_size x seqlen_k x num_heads_k x head_size
  695. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
  696. const float p_dropout, // probability to drop
  697. const float softmax_scale,
  698. const bool is_causal,
  699. int window_size_left,
  700. int window_size_right,
  701. const float softcap,
  702. const bool deterministic,
  703. c10::optional<at::Generator> gen_,
  704. c10::optional<at::Tensor> &rng_state) {
  705. #ifdef FLASHATTENTION_DISABLE_BACKWARD
  706. TORCH_CHECK(false, "This flash attention build does not support backward.");
  707. #endif
  708. if (is_causal) { window_size_right = 0; }
  709. // Otherwise the kernel will be launched from cuda:0 device
  710. at::cuda::CUDAGuard device_guard{q.device()};
  711. auto [cc_major, cc_minor] = get_compute_capability(get_current_device());
  712. // bool is_sm75 = cc_major == 7 && cc_minor == 5;
  713. bool is_sm8x = cc_major == 8 && cc_minor >= 0;
  714. bool is_sm80 = cc_major == 8 && cc_minor == 0;
  715. bool is_sm90 = cc_major == 9 && cc_minor == 0;
  716. TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
  717. // We will support Turing in the near future
  718. // TORCH_CHECK(is_sm90 || is_sm8x || is_sm75, "FlashAttention only supports Turing GPUs or newer.");
  719. bool is_dropout = p_dropout > 0.0;
  720. auto stream = at::cuda::getCurrentCUDAStream().stream();
  721. auto q_dtype = q.dtype();
  722. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  723. "FlashAttention only support fp16 and bf16 data type");
  724. if (q_dtype == torch::kBFloat16) {
  725. TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
  726. }
  727. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  728. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  729. TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
  730. TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
  731. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  732. CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
  733. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  734. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  735. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  736. TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
  737. TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
  738. const auto sizes = q.sizes();
  739. const int batch_size = sizes[0];
  740. const int seqlen_q = sizes[1];
  741. const int num_heads = sizes[2];
  742. const int head_size = sizes[3];
  743. const int seqlen_k = k.size(1);
  744. const int num_heads_k = k.size(2);
  745. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  746. TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
  747. TORCH_CHECK(head_size <= 256, "FlashAttention backward only supports head dimension at most 256");
  748. if (head_size > 192 && is_dropout) {
  749. TORCH_CHECK(is_sm80 || is_sm90, "FlashAttention backward for head dim > 192 with dropout requires A100/A800 or H100/H800");
  750. }
  751. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  752. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  753. const int head_size_rounded = head_size <= 192 ? round_multiple(head_size, 32) : 256;
  754. const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
  755. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  756. if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }
  757. if (window_size_left >= seqlen_k) { window_size_left = -1; }
  758. if (window_size_right >= seqlen_k) { window_size_right = -1; }
  759. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size);
  760. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size);
  761. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size);
  762. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size);
  763. CHECK_SHAPE(dout, batch_size, seqlen_q, num_heads, head_size);
  764. at::Tensor dq, dk, dv;
  765. if (dq_.has_value()) {
  766. dq = dq_.value();
  767. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  768. CHECK_DEVICE(dq);
  769. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  770. CHECK_SHAPE(dq, batch_size, seqlen_q, num_heads, head_size);
  771. } else {
  772. dq = torch::empty_like(q);
  773. }
  774. if (dk_.has_value()) {
  775. dk = dk_.value();
  776. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  777. CHECK_DEVICE(dk);
  778. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  779. CHECK_SHAPE(dk, batch_size, seqlen_k, num_heads_k, head_size);
  780. } else {
  781. dk = torch::empty_like(k);
  782. }
  783. if (dv_.has_value()) {
  784. dv = dv_.value();
  785. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  786. CHECK_DEVICE(dv);
  787. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  788. CHECK_SHAPE(dv, batch_size, seqlen_k, num_heads_k, head_size);
  789. } else {
  790. dv = torch::empty_like(v);
  791. }
  792. // bool loop = seqlen_k > blocksize_c;
  793. // TODO: change later, for now set to true for simplicity
  794. bool loop = true;
  795. auto opts = q.options();
  796. auto softmax_d = torch::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
  797. at::Tensor dq_accum;
  798. at::Tensor dk_accum, dv_accum;
  799. if (loop) {
  800. if (!deterministic) {
  801. dq_accum = torch::empty({batch_size, seqlen_q_rounded, num_heads, head_size_rounded}, opts.dtype(at::kFloat));
  802. } else {
  803. const int nsplits = (get_num_sm(get_current_device()) + batch_size * num_heads - 1) / (batch_size * num_heads);
  804. dq_accum = torch::zeros({nsplits, batch_size, seqlen_q_rounded, num_heads, head_size_rounded}, opts.dtype(at::kFloat));
  805. }
  806. // dk_accum = torch::empty({batch_size, num_heads_k, seqlen_k_rounded, head_size_rounded}, opts.dtype(at::kFloat));
  807. // dv_accum = torch::empty({batch_size, num_heads_k, seqlen_k_rounded, head_size_rounded}, opts.dtype(at::kFloat));
  808. }
  809. at::Tensor dk_expanded, dv_expanded;
  810. if (num_heads_k != num_heads) { // MQA / GQA
  811. dk_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  812. dv_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  813. } else {
  814. dk_expanded = dk;
  815. dv_expanded = dv;
  816. }
  817. Flash_bwd_params params;
  818. set_params_dgrad(params,
  819. batch_size,
  820. seqlen_q, seqlen_k,
  821. seqlen_q_rounded, seqlen_k_rounded,
  822. num_heads, num_heads_k,
  823. head_size, head_size_rounded,
  824. q, k, v, out,
  825. dout, dq, dk_expanded, dv_expanded,
  826. nullptr,
  827. nullptr,
  828. loop ? dq_accum.data_ptr() : nullptr,
  829. // loop ? dk_accum.data_ptr() : nullptr,
  830. // loop ? dv_accum.data_ptr() : nullptr,
  831. nullptr,
  832. nullptr,
  833. softmax_lse.data_ptr(),
  834. softmax_d.data_ptr(),
  835. p_dropout,
  836. softmax_scale,
  837. window_size_left,
  838. window_size_right,
  839. softcap,
  840. deterministic,
  841. /*unpadded_lse*/false);
  842. params.dq_accum_split_stride = !deterministic ? 0 : dq_accum.stride(0);
  843. auto launch = &run_mha_bwd;
  844. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  845. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  846. // We use a custom RNG that increases the offset by batch_size * nheads * 32.
  847. int64_t counter_offset = params.b * params.h * 32;
  848. if ( rng_state.has_value() ) {
  849. params.rng_state = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
  850. } else if( is_dropout ) {
  851. // See Note [Acquire lock when using random generators]
  852. std::lock_guard<std::mutex> lock(gen->mutex_);
  853. params.philox_args = gen->philox_cuda_state(counter_offset);
  854. auto seeds = at::cuda::philox::unpack(params.philox_args);
  855. params.rng_state[0] = std::get<0>(seeds);
  856. params.rng_state[1] = std::get<1>(seeds);
  857. }
  858. set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
  859. if (seqlen_q > 0) {
  860. launch(params, stream);
  861. } else {
  862. // If seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  863. dk_expanded.zero_();
  864. dv_expanded.zero_();
  865. softmax_d.zero_();
  866. }
  867. // For MQA/GQA we need to sum dK and dV across the groups
  868. if (num_heads_k != num_heads) {
  869. at::sum_out(dk, at::reshape(dk_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  870. at::sum_out(dv, at::reshape(dv_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  871. }
  872. return { dq, dk, dv, softmax_d };
  873. }
  874. std::vector<at::Tensor>
  875. mha_varlen_bwd(const at::Tensor &dout, // total_q x num_heads, x head_size
  876. const at::Tensor &q, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
  877. const at::Tensor &k, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
  878. const at::Tensor &v, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
  879. const at::Tensor &out, // total_q x num_heads x head_size
  880. const at::Tensor &softmax_lse, // h x total_q, softmax logsumexp
  881. c10::optional<at::Tensor> &dq_, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
  882. c10::optional<at::Tensor> &dk_, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
  883. c10::optional<at::Tensor> &dv_, // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
  884. const at::Tensor &cu_seqlens_q, // b+1
  885. const at::Tensor &cu_seqlens_k, // b+1
  886. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or b x num_heads
  887. const int max_seqlen_q,
  888. const int max_seqlen_k, // max sequence length to choose the kernel
  889. const float p_dropout, // probability to drop
  890. const float softmax_scale,
  891. const bool zero_tensors,
  892. const bool is_causal,
  893. int window_size_left,
  894. int window_size_right,
  895. const float softcap,
  896. const bool deterministic,
  897. c10::optional<at::Generator> gen_,
  898. c10::optional<at::Tensor> &rng_state) {
  899. #ifdef FLASHATTENTION_DISABLE_BACKWARD
  900. TORCH_CHECK(false, "This flash attention build does not support backward.");
  901. #endif
  902. if (is_causal) { window_size_right = 0; }
  903. // Otherwise the kernel will be launched from cuda:0 device
  904. at::cuda::CUDAGuard device_guard{q.device()};
  905. auto [cc_major, cc_minor] = get_compute_capability(get_current_device());
  906. // bool is_sm75 = cc_major == 7 && cc_minor == 5;
  907. bool is_sm8x = cc_major == 8 && cc_minor >= 0;
  908. bool is_sm80 = cc_major == 8 && cc_minor == 0;
  909. bool is_sm90 = cc_major == 9 && cc_minor == 0;
  910. TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
  911. // We will support Turing in the near future
  912. // TORCH_CHECK(is_sm90 || is_sm8x || is_sm75, "FlashAttention only supports Turing GPUs or newer.");
  913. bool is_dropout = p_dropout > 0.0;
  914. auto stream = at::cuda::getCurrentCUDAStream().stream();
  915. auto q_dtype = q.dtype();
  916. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  917. "FlashAttention only support fp16 and bf16 data type");
  918. if (q_dtype == torch::kBFloat16) {
  919. TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
  920. }
  921. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  922. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  923. TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
  924. TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
  925. TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
  926. TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");
  927. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  928. CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
  929. CHECK_DEVICE(cu_seqlens_q); CHECK_DEVICE(cu_seqlens_k);
  930. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  931. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  932. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  933. TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
  934. TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
  935. CHECK_CONTIGUOUS(cu_seqlens_q);
  936. CHECK_CONTIGUOUS(cu_seqlens_k);
  937. const auto sizes = q.sizes();
  938. const int total_q = sizes[0];
  939. const int batch_size = cu_seqlens_q.numel() - 1;
  940. const int num_heads = sizes[1];
  941. const int head_size = sizes[2];
  942. const int total_k = k.size(0);
  943. const int num_heads_k = k.size(1);
  944. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  945. TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
  946. TORCH_CHECK(head_size <= 256, "FlashAttention backward only supports head dimension at most 256");
  947. if (head_size > 192 && is_dropout) {
  948. TORCH_CHECK(is_sm80 || is_sm90, "FlashAttention backward for head dim > 192 with dropout requires A100/A800 or H100/H800");
  949. }
  950. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  951. if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }
  952. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  953. const int head_size_rounded = head_size <= 192 ? round_multiple(head_size, 32) : 256;
  954. const int seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
  955. const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
  956. if (window_size_left >= max_seqlen_k) { window_size_left = -1; }
  957. if (window_size_right >= max_seqlen_k) { window_size_right = -1; }
  958. CHECK_SHAPE(q, total_q, num_heads, head_size);
  959. CHECK_SHAPE(k, total_k, num_heads_k, head_size);
  960. CHECK_SHAPE(v, total_k, num_heads_k, head_size);
  961. CHECK_SHAPE(out, total_q, num_heads, head_size);
  962. CHECK_SHAPE(dout, total_q, num_heads, head_size);
  963. CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
  964. CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
  965. at::Tensor dq, dk, dv;
  966. if (dq_.has_value()) {
  967. dq = dq_.value();
  968. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  969. CHECK_DEVICE(dq);
  970. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  971. CHECK_SHAPE(dq, total_q, num_heads, head_size);
  972. } else {
  973. dq = torch::empty_like(q);
  974. }
  975. if (dk_.has_value()) {
  976. dk = dk_.value();
  977. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  978. CHECK_DEVICE(dk);
  979. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  980. CHECK_SHAPE(dk, total_k, num_heads_k, head_size);
  981. } else {
  982. dk = torch::empty_like(k);
  983. }
  984. if (dv_.has_value()) {
  985. dv = dv_.value();
  986. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  987. CHECK_DEVICE(dv);
  988. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  989. CHECK_SHAPE(dv, total_k, num_heads_k, head_size);
  990. } else {
  991. dv = torch::empty_like(v);
  992. }
  993. // bool loop = max_seqlen_k > blocksize_c;
  994. // TODO: change later, for now set to true for simplicity
  995. bool loop = true;
  996. auto opts = q.options();
  997. auto softmax_d = torch::empty({num_heads, total_q + 128 * batch_size}, opts.dtype(at::kFloat));
  998. at::Tensor dq_accum;
  999. if (loop) {
  1000. // We don't want to allocate dq_accum of size (batch, seqlen_q_rounded, num_heads, head_size_rounded)
  1001. // because that would be too large if there is a very long sequence and the rest of the sequences are short.
  1002. // Instead, we allocate dq_accum of size (total_q + 128 * batch, num_heads, head_size_rounded).
  1003. // Note that 128 is the max block size on the seqlen_q dimension.
  1004. // For dQ, the i-th sequence is stored in indices from cu_seqlens[i] + 128 * i to
  1005. // cu_seqlens[i + 1] * 128 * i - 1. This ensures that the i-th sequence and (i + 1)-th sequence will
  1006. // be at least 128 apart. It's ok for us to do atomicAdds up to 128 rows beyond what we're normally
  1007. // allowed to do. So we won't have to do any bound checking, and performance should stay the same.
  1008. // Same holds for softmax_d, since LSE is stored in unpadded format.
  1009. if (!deterministic) {
  1010. dq_accum = torch::empty({total_q + 128 * batch_size, num_heads, head_size_rounded}, opts.dtype(at::kFloat));
  1011. } else {
  1012. const int nsplits = (get_num_sm(get_current_device()) + batch_size * num_heads - 1) / (batch_size * num_heads);
  1013. dq_accum = torch::zeros({nsplits, total_q + 128 * batch_size, num_heads, head_size_rounded}, opts.dtype(at::kFloat));
  1014. }
  1015. }
  1016. at::Tensor dk_expanded, dv_expanded;
  1017. if (num_heads_k != num_heads) { // MQA / GQA
  1018. dk_expanded = torch::empty({total_k, num_heads, head_size}, opts);
  1019. dv_expanded = torch::empty({total_k, num_heads, head_size}, opts);
  1020. } else {
  1021. dk_expanded = dk;
  1022. dv_expanded = dv;
  1023. }
  1024. if( zero_tensors ) {
  1025. dq.zero_();
  1026. dk_expanded.zero_();
  1027. dv_expanded.zero_();
  1028. softmax_d.zero_();
  1029. }
  1030. Flash_bwd_params params;
  1031. set_params_dgrad(params,
  1032. batch_size,
  1033. max_seqlen_q, max_seqlen_k,
  1034. seqlen_q_rounded, seqlen_k_rounded,
  1035. num_heads, num_heads_k,
  1036. head_size, head_size_rounded,
  1037. q, k, v, out,
  1038. dout, dq, dk_expanded, dv_expanded,
  1039. cu_seqlens_q.data_ptr(),
  1040. cu_seqlens_k.data_ptr(),
  1041. loop ? dq_accum.data_ptr() : nullptr,
  1042. nullptr,
  1043. nullptr,
  1044. softmax_lse.data_ptr(),
  1045. softmax_d.data_ptr(),
  1046. p_dropout,
  1047. softmax_scale,
  1048. window_size_left,
  1049. window_size_right,
  1050. softcap,
  1051. deterministic,
  1052. /*unpadded_lse*/true);
  1053. params.dq_accum_split_stride = !deterministic ? 0 : dq_accum.stride(0);
  1054. params.total_q = total_q;
  1055. auto launch = &run_mha_bwd;
  1056. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  1057. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  1058. // We use a custom RNG that increases the offset by batch_size * nheads * 32.
  1059. int64_t counter_offset = params.b * params.h * 32;
  1060. if ( rng_state.has_value() ) {
  1061. params.rng_state = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
  1062. } else if( is_dropout ) {
  1063. // See Note [Acquire lock when using random generators]
  1064. std::lock_guard<std::mutex> lock(gen->mutex_);
  1065. params.philox_args = gen->philox_cuda_state(counter_offset);
  1066. auto seeds = at::cuda::philox::unpack(params.philox_args);
  1067. params.rng_state[0] = std::get<0>(seeds);
  1068. params.rng_state[1] = std::get<1>(seeds);
  1069. }
  1070. set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
  1071. if (max_seqlen_q > 0) {
  1072. launch(params, stream);
  1073. } else {
  1074. // If seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  1075. dk_expanded.zero_();
  1076. dv_expanded.zero_();
  1077. softmax_d.zero_();
  1078. }
  1079. // For MQA/GQA we need to sum dK and dV across the groups
  1080. if (num_heads_k != num_heads) {
  1081. at::sum_out(dk, at::reshape(dk_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
  1082. at::sum_out(dv, at::reshape(dv_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
  1083. }
  1084. return { dq, dk, dv, softmax_d };
  1085. }
  1086. std::vector<at::Tensor>
  1087. mha_fwd_kvcache(at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  1088. const at::Tensor &kcache, // batch_size_c x seqlen_k x num_heads_k x head_size or num_blocks x page_block_size x num_heads_k x head_size if there's a block_table.
  1089. const at::Tensor &vcache, // batch_size_c x seqlen_k x num_heads_k x head_size or num_blocks x page_block_size x num_heads_k x head_size if there's a block_table.
  1090. c10::optional<const at::Tensor> &k_, // batch_size x seqlen_knew x num_heads_k x head_size
  1091. c10::optional<const at::Tensor> &v_, // batch_size x seqlen_knew x num_heads_k x head_size
  1092. c10::optional<const at::Tensor> &seqlens_k_, // batch_size
  1093. c10::optional<const at::Tensor> &rotary_cos_, // seqlen_ro x (rotary_dim / 2)
  1094. c10::optional<const at::Tensor> &rotary_sin_, // seqlen_ro x (rotary_dim / 2)
  1095. c10::optional<const at::Tensor> &cache_batch_idx_, // indices to index into the KV cache
  1096. c10::optional<const at::Tensor> &leftpad_k_, // batch_size
  1097. c10::optional<at::Tensor> &block_table_, // batch_size x max_num_blocks_per_seq
  1098. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
  1099. c10::optional<at::Tensor> &out_, // batch_size x seqlen_q x num_heads x head_size
  1100. const float softmax_scale,
  1101. bool is_causal,
  1102. int window_size_left,
  1103. int window_size_right,
  1104. const float softcap,
  1105. bool is_rotary_interleaved, // if true, rotary combines indices 0 & 1, else indices 0 & rotary_dim / 2
  1106. int num_splits
  1107. ) {
  1108. // Otherwise the kernel will be launched from cuda:0 device
  1109. at::cuda::CUDAGuard device_guard{q.device()};
  1110. auto [cc_major, cc_minor] = get_compute_capability(get_current_device());
  1111. // bool is_sm75 = cc_major == 7 && cc_minor == 5;
  1112. bool is_sm8x = cc_major == 8 && cc_minor >= 0;
  1113. bool is_sm90 = cc_major == 9 && cc_minor == 0;
  1114. TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
  1115. // We will support Turing in the near future
  1116. // TORCH_CHECK(is_sm90 || is_sm8x || is_sm75, "FlashAttention only supports Turing GPUs or newer.");
  1117. auto q_dtype = q.dtype();
  1118. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  1119. "FlashAttention only support fp16 and bf16 data type");
  1120. if (q_dtype == torch::kBFloat16) {
  1121. TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
  1122. }
  1123. TORCH_CHECK(kcache.dtype() == q_dtype, "query and key must have the same dtype");
  1124. TORCH_CHECK(vcache.dtype() == q_dtype, "query and value must have the same dtype");
  1125. CHECK_DEVICE(q); CHECK_DEVICE(kcache); CHECK_DEVICE(vcache);
  1126. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1127. TORCH_CHECK(kcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1128. TORCH_CHECK(vcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1129. at::Tensor block_table;
  1130. const bool paged_KV = block_table_.has_value();
  1131. if (paged_KV) {
  1132. TORCH_CHECK(!cache_batch_idx_.has_value(), "Paged KVcache does not support cache_batch_idx");
  1133. block_table = block_table_.value();
  1134. CHECK_DEVICE(block_table);
  1135. TORCH_CHECK(block_table.dtype() == torch::kInt32, "block_table must have dtype torch.int32");
  1136. TORCH_CHECK(block_table.stride(-1) == 1, "block_table must have contiguous last dimension");
  1137. }
  1138. const auto sizes = q.sizes();
  1139. const int batch_size = sizes[0];
  1140. int seqlen_q = sizes[1];
  1141. int num_heads = sizes[2];
  1142. const int head_size_og = sizes[3];
  1143. const int max_num_blocks_per_seq = !paged_KV ? 0 : block_table.size(1);
  1144. const int num_blocks = !paged_KV ? 0 : kcache.size(0);
  1145. const int page_block_size = !paged_KV ? 1 : kcache.size(1);
  1146. TORCH_CHECK(!paged_KV || page_block_size % 256 == 0, "Paged KV cache block size must be divisible by 256");
  1147. const int seqlen_k = !paged_KV ? kcache.size(1) : max_num_blocks_per_seq * page_block_size;
  1148. const int num_heads_k = kcache.size(2);
  1149. const int batch_size_c = !paged_KV ? kcache.size(0) : batch_size;
  1150. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  1151. TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
  1152. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  1153. // causal=true is the same as causal=false in this case
  1154. if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }
  1155. if (is_causal) { window_size_right = 0; }
  1156. // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
  1157. // H/t Daniel Haziza
  1158. const int seqlenq_ngroups_swapped = seqlen_q == 1 && num_heads > num_heads_k && window_size_left < 0 && window_size_right < 0 && head_size_og % 8 == 0 && !alibi_slopes_.has_value();
  1159. if (seqlenq_ngroups_swapped) {
  1160. const int ngroups = num_heads / num_heads_k;
  1161. q = q.reshape({batch_size, num_heads_k, ngroups, head_size_og}).transpose(1, 2);
  1162. seqlen_q = ngroups;
  1163. num_heads = num_heads_k;
  1164. }
  1165. if (window_size_left >= seqlen_k) { window_size_left = -1; }
  1166. if (window_size_right >= seqlen_k) { window_size_right = -1; }
  1167. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
  1168. if (!paged_KV) {
  1169. CHECK_SHAPE(kcache, batch_size_c, seqlen_k, num_heads_k, head_size_og);
  1170. CHECK_SHAPE(vcache, batch_size_c, seqlen_k, num_heads_k, head_size_og);
  1171. } else {
  1172. CHECK_SHAPE(kcache, num_blocks, page_block_size, num_heads_k, head_size_og);
  1173. CHECK_SHAPE(vcache, num_blocks, page_block_size, num_heads_k, head_size_og);
  1174. CHECK_SHAPE(block_table, batch_size, max_num_blocks_per_seq);
  1175. }
  1176. at::Tensor q_padded, kcache_padded, vcache_padded;
  1177. if (head_size_og % 8 != 0) {
  1178. q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1179. kcache_padded = torch::nn::functional::pad(kcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1180. vcache_padded = torch::nn::functional::pad(vcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1181. } else {
  1182. q_padded = q;
  1183. kcache_padded = kcache;
  1184. vcache_padded = vcache;
  1185. }
  1186. at::Tensor out;
  1187. if (out_.has_value()) {
  1188. out = out_.value();
  1189. TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  1190. CHECK_DEVICE(out);
  1191. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  1192. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og);
  1193. if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
  1194. } else {
  1195. out = torch::empty_like(q_padded);
  1196. }
  1197. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  1198. const int head_size = round_multiple(head_size_og, 8);
  1199. const int head_size_rounded = head_size <= 192 ? round_multiple(head_size, 32) : 256;
  1200. const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
  1201. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  1202. auto opts = q.options();
  1203. auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  1204. Flash_fwd_params params;
  1205. set_params_fprop(params,
  1206. batch_size,
  1207. seqlen_q, seqlen_k,
  1208. seqlen_q_rounded, seqlen_k_rounded,
  1209. num_heads, num_heads_k,
  1210. head_size, head_size_rounded,
  1211. q_padded, kcache_padded, vcache_padded, out,
  1212. /*cu_seqlens_q_d=*/nullptr,
  1213. /*cu_seqlens_k_d=*/nullptr,
  1214. /*seqused_k=*/nullptr,
  1215. /*p_ptr=*/nullptr,
  1216. softmax_lse.data_ptr(),
  1217. /*p_dropout=*/0.f,
  1218. softmax_scale,
  1219. window_size_left,
  1220. window_size_right,
  1221. softcap
  1222. );
  1223. at::Tensor k, v, k_padded, v_padded;
  1224. if (k_.has_value()) {
  1225. TORCH_CHECK(v_.has_value(), "If key is supplied, value must also be passed in");
  1226. TORCH_CHECK(seqlens_k_.has_value(), "If key is supplied, seqlens_k must also be passed in");
  1227. TORCH_CHECK(seqlen_q <= seqlen_k, "If key is supplied, it must have seqlen <= the seqlen of the KV cache");
  1228. k = k_.value();
  1229. v = v_.value();
  1230. TORCH_CHECK(k.dtype() == q_dtype, "Key must have the same dtype as query");
  1231. TORCH_CHECK(v.dtype() == q_dtype, "Value must have the same dtype as query");
  1232. CHECK_DEVICE(k); CHECK_DEVICE(v);
  1233. TORCH_CHECK(k.stride(-1) == 1, "Key tensor must have contiguous last dimension");
  1234. TORCH_CHECK(v.stride(-1) == 1, "Value tensor must have contiguous last dimension");
  1235. int seqlen_knew = k.size(1);
  1236. CHECK_SHAPE(k, batch_size, seqlen_knew, num_heads_k, head_size_og);
  1237. CHECK_SHAPE(v, batch_size, seqlen_knew, num_heads_k, head_size_og);
  1238. if (head_size_og % 8 != 0) {
  1239. k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1240. v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1241. } else {
  1242. k_padded = k;
  1243. v_padded = v;
  1244. }
  1245. params.seqlen_knew = seqlen_knew;
  1246. params.knew_ptr = k_padded.data_ptr();
  1247. params.vnew_ptr = v_padded.data_ptr();
  1248. // All stride are in elements, not bytes.
  1249. params.knew_batch_stride = k_padded.stride(0);
  1250. params.vnew_batch_stride = v_padded.stride(0);
  1251. params.knew_row_stride = k_padded.stride(-3);
  1252. params.vnew_row_stride = v_padded.stride(-3);
  1253. params.knew_head_stride = k_padded.stride(-2);
  1254. params.vnew_head_stride = v_padded.stride(-2);
  1255. }
  1256. if (seqlens_k_.has_value()) {
  1257. auto seqlens_k = seqlens_k_.value();
  1258. TORCH_CHECK(seqlens_k.dtype() == torch::kInt32, "seqlens_k must have dtype int32");
  1259. CHECK_DEVICE(seqlens_k);
  1260. CHECK_CONTIGUOUS(seqlens_k);
  1261. CHECK_SHAPE(seqlens_k, batch_size);
  1262. params.cu_seqlens_k = static_cast<int *>(seqlens_k.data_ptr());
  1263. }
  1264. params.is_seqlens_k_cumulative = !(seqlens_k_.has_value());
  1265. if (leftpad_k_.has_value()) {
  1266. TORCH_CHECK(!paged_KV, "We don't support Paged KV and leftpad_k running at the same time yet");
  1267. auto leftpad_k = leftpad_k_.value();
  1268. TORCH_CHECK(leftpad_k.dtype() == torch::kInt32, "leftpad_k must have dtype int32");
  1269. CHECK_DEVICE(leftpad_k);
  1270. CHECK_CONTIGUOUS(leftpad_k);
  1271. CHECK_SHAPE(leftpad_k, batch_size);
  1272. params.leftpad_k = static_cast<int *>(leftpad_k.data_ptr());
  1273. }
  1274. if (rotary_cos_.has_value()) {
  1275. TORCH_CHECK(k_.has_value(), "If rotary cos/sin are provided, new key / value to be appended to KV cache must also be provided");
  1276. auto rotary_cos = rotary_cos_.value();
  1277. CHECK_DEVICE(rotary_cos);
  1278. params.rotary_dim = rotary_cos.size(1) * 2;
  1279. TORCH_CHECK(params.rotary_dim <= head_size, "rotary_dim must be <= headdim");
  1280. TORCH_CHECK(params.rotary_dim % 16 == 0, "Only rotary dimensions divisible by 16 are currently supported");
  1281. const int seqlen_ro = rotary_cos.size(0);
  1282. TORCH_CHECK(seqlen_ro >= seqlen_k, "cos/sin seqlen must be at least the seqlen of KV cache");
  1283. CHECK_SHAPE(rotary_cos, seqlen_ro, params.rotary_dim / 2);
  1284. CHECK_CONTIGUOUS(rotary_cos);
  1285. TORCH_CHECK(rotary_cos.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");
  1286. TORCH_CHECK(rotary_sin_.has_value(), "If rotary cos is provided, rotary sin must also be provided");
  1287. auto rotary_sin = rotary_sin_.value();
  1288. CHECK_DEVICE(rotary_sin);
  1289. CHECK_SHAPE(rotary_sin, seqlen_ro, params.rotary_dim / 2);
  1290. CHECK_CONTIGUOUS(rotary_sin);
  1291. TORCH_CHECK(rotary_sin.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");
  1292. params.rotary_cos_ptr = rotary_cos.data_ptr();
  1293. params.rotary_sin_ptr = rotary_sin.data_ptr();
  1294. params.is_rotary_interleaved = is_rotary_interleaved;
  1295. } else {
  1296. params.rotary_dim = 0;
  1297. }
  1298. if (cache_batch_idx_.has_value()) {
  1299. auto cache_batch_idx = cache_batch_idx_.value();
  1300. CHECK_DEVICE(cache_batch_idx);
  1301. CHECK_CONTIGUOUS(cache_batch_idx);
  1302. TORCH_CHECK(cache_batch_idx.scalar_type() == torch::kInt32, "cache_batch_idx must have dtype int32");
  1303. params.cache_batch_idx = reinterpret_cast<int *>(cache_batch_idx.data_ptr());
  1304. }
  1305. // Keep references to these tensors to extend their lifetime
  1306. at::Tensor softmax_lse_accum, out_accum;
  1307. std::tie(softmax_lse_accum, out_accum) = set_params_splitkv(
  1308. params, batch_size, num_heads, head_size, seqlen_k, seqlen_q,
  1309. head_size_rounded, /*dropout*/ 0.f, num_splits, get_num_sm(get_current_device()), opts);
  1310. if (paged_KV) {
  1311. params.block_table = block_table.data_ptr<int>();
  1312. params.block_table_batch_stride = block_table.stride(0);
  1313. }
  1314. params.page_block_size = page_block_size;
  1315. set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
  1316. auto stream = at::cuda::getCurrentCUDAStream().stream();
  1317. // Only split kernel supports appending to KV cache, or indexing to the cache with cache_batch_idx,
  1318. // or paged KV cache
  1319. run_mha_fwd(params, stream, /*force_split_kernel=*/k_.has_value() || cache_batch_idx_.has_value() || paged_KV);
  1320. if (head_size_og % 8 != 0) {
  1321. out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1322. if (out_.has_value()) { out_.value().copy_(out); }
  1323. if (k_.has_value()) {
  1324. // It's expensive to copy the KV cache here for the case where head size not divisible by 8,
  1325. // but we don't expect to get this case in practice. This is just so that the code works for that case.
  1326. kcache.copy_(kcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
  1327. vcache.copy_(vcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
  1328. }
  1329. }
  1330. if (seqlenq_ngroups_swapped) {
  1331. out = out.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size_og});
  1332. softmax_lse = softmax_lse.reshape({batch_size, num_heads_k * seqlen_q, 1});
  1333. }
  1334. return {out, softmax_lse};
  1335. }
  1336. PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  1337. m.doc() = "FlashAttention";
  1338. m.def("fwd", &mha_fwd, "Forward pass");
  1339. m.def("varlen_fwd", &mha_varlen_fwd, "Forward pass (variable length)");
  1340. m.def("bwd", &mha_bwd, "Backward pass");
  1341. m.def("varlen_bwd", &mha_varlen_bwd, "Backward pass (variable length)");
  1342. m.def("fwd_kvcache", &mha_fwd_kvcache, "Forward pass, with KV-cache");
  1343. }