1
0

flash_api.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. /******************************************************************************
  2. * Copyright (c) 2024, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, 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 <ATen/cuda/CUDAContext.h>
  8. #include <c10/cuda/CUDAGuard.h>
  9. #include <cutlass/numeric_types.h>
  10. #include "flash.h"
  11. #include "static_switch.h"
  12. #define CHECK_DEVICE(x) TORCH_CHECK(x.is_cuda(), #x " must be on CUDA")
  13. #define CHECK_SHAPE(x, ...) TORCH_CHECK(x.sizes() == torch::IntArrayRef({__VA_ARGS__}), #x " must have shape (" #__VA_ARGS__ ")")
  14. #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
  15. void set_params_fprop(Flash_fwd_params &params,
  16. // sizes
  17. const size_t b,
  18. const size_t b_k,
  19. const size_t seqlen_q,
  20. const size_t seqlen_k,
  21. const size_t seqlen_q_rounded,
  22. const size_t seqlen_k_rounded,
  23. const size_t h,
  24. const size_t h_k,
  25. const size_t d,
  26. const size_t d_rounded,
  27. // device pointers
  28. const at::Tensor q,
  29. const at::Tensor k,
  30. const at::Tensor v,
  31. at::Tensor out,
  32. void *cu_seqlens_q_d,
  33. void *cu_seqlens_k_d,
  34. void *seqused_q,
  35. void *seqused_k,
  36. void *p_d,
  37. void *softmax_lse_d,
  38. float p_dropout,
  39. float softmax_scale,
  40. int window_size_left,
  41. int window_size_right,
  42. bool seqlenq_ngroups_swapped=false,
  43. bool unpadded_lse=false) {
  44. // Reset the parameters
  45. params = {};
  46. params.is_bf16 = q.dtype() == torch::kBFloat16;
  47. params.is_e4m3 = q.dtype() == torch::kFloat8_e4m3fn;
  48. params.is_kv_cache = false;
  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_q = static_cast<int *>(seqused_q);
  76. params.seqused_k = static_cast<int *>(seqused_k);
  77. TORCH_CHECK(
  78. bool(params.cu_seqlens_q) == bool(params.cu_seqlens_k),
  79. "cu_seqlens_q and cu_seqlens_k must be both null or non-null"
  80. );
  81. // P = softmax(QK^T)
  82. params.p_ptr = p_d;
  83. // Softmax sum
  84. params.softmax_lse_ptr = softmax_lse_d;
  85. // Set the dimensions.
  86. params.b = b;
  87. params.b_k = b_k;
  88. params.h = h;
  89. params.h_k = h_k;
  90. params.h_h_k_ratio = h / h_k;
  91. params.seqlen_q = seqlen_q;
  92. params.seqlen_k = seqlen_k;
  93. params.seqlen_q_rounded = seqlen_q_rounded;
  94. params.seqlen_k_rounded = seqlen_k_rounded;
  95. params.d = d;
  96. params.d_rounded = d_rounded;
  97. // Set the different scale values.
  98. params.scale_softmax = softmax_scale;
  99. params.scale_softmax_log2 = softmax_scale * M_LOG2E;
  100. __half scale_softmax_log2_half = __float2half(params.scale_softmax_log2);
  101. __half2 scale_softmax_log2_half2 = __half2(scale_softmax_log2_half, scale_softmax_log2_half);
  102. params.scale_softmax_log2_half2 = reinterpret_cast<uint32_t&>(scale_softmax_log2_half2);
  103. // Set this to probability of keeping an element to simplify things.
  104. params.p_dropout = 1.f - p_dropout;
  105. // Convert p from float to int so we don't have to convert the random uint to float to compare.
  106. // [Minor] We want to round down since when we do the comparison we use <= instead of <
  107. // params.p_dropout_in_uint = uint32_t(std::floor(params.p_dropout * 4294967295.0));
  108. // params.p_dropout_in_uint16_t = uint16_t(std::floor(params.p_dropout * 65535.0));
  109. params.p_dropout_in_uint8_t = uint8_t(std::floor(params.p_dropout * 255.0));
  110. params.rp_dropout = 1.f / params.p_dropout;
  111. params.scale_softmax_rp_dropout = params.rp_dropout * params.scale_softmax;
  112. TORCH_CHECK(p_dropout < 1.f);
  113. #ifdef FLASHATTENTION_DISABLE_DROPOUT
  114. TORCH_CHECK(p_dropout == 0.0f, "This flash attention build does not support dropout.");
  115. #endif
  116. // Causal is the special case where window_size_right == 0 and window_size_left < 0.
  117. // Local is the more general case where window_size_right >= 0 or window_size_left >= 0.
  118. window_size_left = std::min(int(seqlen_k), window_size_left);
  119. window_size_right = std::min(int(seqlen_k), window_size_right);
  120. if (window_size_left < 0) { window_size_left = seqlen_k; }
  121. if (window_size_right < 0) { window_size_right = seqlen_k; }
  122. params.window_size_left = window_size_left;
  123. params.window_size_right = window_size_right;
  124. params.is_causal = window_size_left == int(seqlen_k) && window_size_right == 0;
  125. if ((window_size_left < int(seqlen_k) || window_size_right < int(seqlen_k)) && !params.is_causal) {
  126. params.is_local = true;
  127. }
  128. #ifdef FLASHATTENTION_DISABLE_LOCAL
  129. TORCH_CHECK(params.is_causal || (window_size_left < 0 && window_size_right < 0),
  130. "This flash attention build does not support local attention.");
  131. #endif
  132. #ifdef FLASHATTENTION_DISABLE_UNEVEN_K
  133. TORCH_CHECK(d == d_rounded, "This flash attention build does not support headdim not being a multiple of 32.");
  134. #endif
  135. params.unpadded_lse = unpadded_lse;
  136. params.seqlenq_ngroups_swapped = seqlenq_ngroups_swapped;
  137. }
  138. void set_params_dgrad(Flash_bwd_params &params,
  139. // sizes
  140. const size_t b,
  141. const size_t seqlen_q,
  142. const size_t seqlen_k,
  143. const size_t seqlen_q_rounded,
  144. const size_t seqlen_k_rounded,
  145. const size_t h,
  146. const size_t h_k,
  147. const size_t d,
  148. const size_t d_rounded,
  149. // device pointers
  150. const at::Tensor q,
  151. const at::Tensor k,
  152. const at::Tensor v,
  153. const at::Tensor out,
  154. const at::Tensor dout,
  155. at::Tensor dq,
  156. at::Tensor dk,
  157. at::Tensor dv,
  158. void *cu_seqlens_q_d,
  159. void *cu_seqlens_k_d,
  160. void *seqused_q,
  161. void *seqused_k,
  162. void *dq_accum_d,
  163. void *dk_accum_d,
  164. void *dv_accum_d,
  165. void *softmax_lse_d,
  166. void *dsoftmax_sum_d,
  167. float p_dropout,
  168. float softmax_scale,
  169. int window_size_left,
  170. int window_size_right,
  171. bool deterministic) {
  172. set_params_fprop(params,
  173. b, b, seqlen_q, seqlen_k, seqlen_q_rounded, seqlen_k_rounded, h, h_k, d, d_rounded,
  174. q, k, v, out,
  175. cu_seqlens_q_d,
  176. cu_seqlens_k_d,
  177. seqused_q,
  178. seqused_k,
  179. nullptr,
  180. softmax_lse_d,
  181. p_dropout,
  182. softmax_scale,
  183. window_size_left,
  184. window_size_right);
  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. // Find the number of splits that maximizes the occupancy. For example, if we have
  212. // batch * n_heads = 48 and we have 108 SMs, having 2 splits (efficiency = 0.89) is
  213. // better than having 3 splits (efficiency = 0.67). However, we also don't want too many
  214. // splits as that would incur more HBM reads/writes.
  215. // So we find the best efficiency, then find the smallest number of splits that gets 80%
  216. // of the best efficiency.
  217. inline int num_splits_heuristic(int batch_nheads_mblocks, int batch_nheads, int num_SMs, int num_n_blocks,
  218. int max_splits, int head_size, bool use_one_mma_wg) {
  219. // Goal of the starting threshold is to determine whether to split or not.
  220. // Empirically, the efficiency threshold can be much lower than 80% depending on num_n_blocks.
  221. int num_m_blocks = batch_nheads_mblocks/batch_nheads;
  222. float start_threshold;
  223. float num_n_blocksf = float(num_n_blocks);
  224. if (head_size == 128) {
  225. if (std::log2f(num_n_blocksf) <= 4) { // 2048 -- .25
  226. start_threshold = .20f + (std::log2f(num_n_blocksf) - 3) * .05f;
  227. } else if (std::log2f(num_n_blocksf) <= 5) { // 4096 -- .25
  228. start_threshold = .25f;
  229. } else if (std::log2f(num_n_blocksf) <= 6) { // 8192 -- .36
  230. start_threshold = .28f + (std::log2f(num_n_blocksf) - 5) * .08f;
  231. } else if (std::log2f(num_n_blocksf) <= 7) { // 16K -- .42
  232. start_threshold = .36f + (std::log2f(num_n_blocksf) - 6) * .06f;
  233. } else {
  234. // Just split freely
  235. start_threshold = .8f;
  236. }
  237. if (num_m_blocks > 1 && start_threshold < .5f)
  238. start_threshold += .05f * (std::log2f(num_n_blocksf) - 2);
  239. } else if (head_size == 256) {
  240. // TODO for hdim 256
  241. if (num_n_blocks <= 40) {
  242. start_threshold = .24f;
  243. } else if (std::log2f(num_n_blocksf) <= 8) {
  244. start_threshold = .33f + std::max(0.f, (std::log2f(num_n_blocksf) - std::log2f(50)) * 0.02971f);
  245. } else {
  246. // Just split freely
  247. start_threshold = .8f;
  248. }
  249. } else if (head_size == 64) {
  250. if (use_one_mma_wg) {
  251. if (std::log2f(num_n_blocksf) <= 4) { // 2K -- .33
  252. start_threshold = .33f;
  253. } else if (std::log2f(num_n_blocksf) <= 5) { // 4K -- .37
  254. start_threshold = .33f + (std::log2f(num_n_blocksf) - 4) * .04f;
  255. } else if (std::log2f(num_n_blocksf) <= 6) { // 8K -- .40
  256. start_threshold = .37f + (std::log2f(num_n_blocksf) - 5) * .03f;
  257. } else if (std::log2f(num_n_blocksf) <= 7) { // 16K -- .43
  258. start_threshold = .4f + (std::log2f(num_n_blocksf) - 6) * .03f;
  259. } else if (std::log2f(num_n_blocksf) <= 8) { // 32K -- .46
  260. start_threshold = .43f + (std::log2f(num_n_blocksf) - 7) * .03f;
  261. } else {
  262. start_threshold = .8f;
  263. }
  264. } else {
  265. if (std::log2f(num_n_blocksf) <= 6) { // 8K -- .5
  266. start_threshold = .5f;
  267. } else {
  268. start_threshold = .8f;
  269. }
  270. }
  271. } else {
  272. // placeholder for other hdims
  273. start_threshold = .8f;
  274. }
  275. float first_wave = float(batch_nheads_mblocks) / num_SMs;
  276. // printf("Start threshold and wave = %f, %f.\n", start_threshold, first_wave);
  277. // Only use start_threshold if initial work doesn't exceed one wave
  278. if ((first_wave/ceil(first_wave) > start_threshold && first_wave <= 1.f) ||
  279. (first_wave/ceil(first_wave) > .8f)) {
  280. return 1;
  281. }
  282. // if (first_wave_batch_nheads > start_threshold) { return 1; }
  283. // if (first_wave_batch_nheads > start_threshold || first_wave > .8f) { return 1; }
  284. // if (float(batch_nheads)/num_SMs > start_threshold) { return 1; }
  285. // If num_n_blocks is too small, use 1 split
  286. // For example, we never split for hdim = 128 and seqlen_k = 512,
  287. // or for hdim = 128, seqlen_k = 1024, and one MMA warpgroup.
  288. if (num_n_blocks < 8 || (use_one_mma_wg && num_n_blocks < 10)) { return 1; }
  289. max_splits = std::min({max_splits, num_SMs, num_n_blocks});
  290. float max_efficiency = 0.f;
  291. std::vector<float> efficiency;
  292. efficiency.reserve(max_splits);
  293. // NOTE: disable split eligibility check for FA3 since we have dynamic tile scheduler
  294. // for exiting splits with no work early, and check leads to efficiency quantization issues.
  295. // Comment from FA2:
  296. // Some splits are not eligible. For example, if we have 64 blocks and choose 11 splits,
  297. // we'll have 6 * 10 + 4 blocks. If we choose 12 splits, we'll have 6 * 11 + (-2) blocks
  298. // (i.e. it's 11 splits anyway).
  299. // So we check if the number of blocks per split is the same as the previous num_splits.
  300. // auto ceildiv = [](int a, int b) { return (a + b - 1) / b; };
  301. // auto is_split_eligible = [&ceildiv, &num_n_blocks](int num_splits) {
  302. // return num_splits == 1 || ceildiv(num_n_blocks, num_splits) != ceildiv(num_n_blocks, num_splits - 1);
  303. // };
  304. for (int num_splits = 1; num_splits <= max_splits; num_splits++) {
  305. // if (!is_split_eligible(num_splits)) {
  306. // efficiency.push_back(0.f);
  307. // } else {
  308. float n_waves = float(batch_nheads_mblocks * num_splits) / num_SMs;
  309. float eff = n_waves / ceil(n_waves);
  310. // printf("num_splits = %d, n_waves = %f, ceil(n_waves) = %f, eff = %f\n", num_splits, n_waves, ceil(n_waves), eff);
  311. if (eff > max_efficiency) { max_efficiency = eff; }
  312. efficiency.push_back(eff);
  313. // }
  314. }
  315. // Correct for excessive splitting with e.g. 1 bsz*nheads*mblocks
  316. // Empirically, efficiency threshold in these cases is about 40% for 64K seqlen_k
  317. float threshold = num_m_blocks == 1 ? std::min(0.3f + batch_nheads * 0.1f, 0.8f) : 0.8f;
  318. threshold = threshold * max_efficiency;
  319. // printf("Max efficiency = %f. Threshold = %f.\n", max_efficiency, threshold);
  320. for (int num_splits = 1; num_splits <= max_splits; num_splits++) {
  321. // if (!is_split_eligible(num_splits)) { continue; }
  322. if (efficiency[num_splits - 1] > threshold) {
  323. // printf("num_splits chosen = %d, threshold = %f, efficiency = %f.\n", num_splits, threshold, efficiency[num_splits - 1]);
  324. return num_splits;
  325. }
  326. }
  327. return 1;
  328. }
  329. std::tuple<at::Tensor, at::Tensor> set_params_splitkv(Flash_fwd_params &params, const int batch_size,
  330. const int num_heads, const int num_heads_k, const int head_size, const int max_seqlen_k, const int max_seqlen_q,
  331. const int head_size_rounded, const float p_dropout,
  332. const int num_splits, cudaDeviceProp *dprops, bool use_gqa_packing, bool is_causal, struct c10::TensorOptions opts) {
  333. auto ceildiv = [](int a, int b) { return (a + b - 1) / b; };
  334. params.num_splits = num_splits;
  335. at::Tensor softmax_lse_accum;
  336. at::Tensor out_accum;
  337. if (p_dropout == 0.0f) { // SplitKV is not implemented for dropout
  338. if (num_splits < 1) {
  339. const int gqa_ratio = num_heads / num_heads_k;
  340. const int block_h = 1 << static_cast<int>(std::ceil(std::log2(std::clamp(gqa_ratio, 1, 32))));
  341. const int block_m = head_size == 64 ? 192 : 128;
  342. const bool use_one_mma_wg = max_seqlen_q <= 64/block_h;
  343. int block_n = 128;
  344. if (head_size == 128 && !is_causal) {
  345. block_n = 176;
  346. } else if (head_size == 256) {
  347. block_n = use_one_mma_wg ? 96 : 80;
  348. }
  349. const int num_n_blocks = (max_seqlen_k + block_n - 1) / block_n;
  350. const int batch_nheads = use_gqa_packing ? batch_size * num_heads_k : batch_size * num_heads;
  351. const int batch_nheads_mblocks = use_gqa_packing
  352. ? ceildiv(max_seqlen_q, block_m / block_h) * batch_nheads
  353. : ceildiv(max_seqlen_q, block_m) * batch_nheads;
  354. params.num_splits = num_splits_heuristic(batch_nheads_mblocks, batch_nheads,
  355. dprops->multiProcessorCount, num_n_blocks, 128, head_size, use_one_mma_wg);
  356. // printf("Num splits heuristic = %d.\n", params.num_splits);
  357. }
  358. if (params.num_splits > 1) {
  359. softmax_lse_accum = torch::empty({params.num_splits, batch_size, num_heads, max_seqlen_q}, opts.dtype(at::kFloat));
  360. out_accum = torch::empty({params.num_splits, batch_size, num_heads, max_seqlen_q, head_size_rounded}, opts.dtype(at::kFloat));
  361. params.softmax_lseaccum_ptr = softmax_lse_accum.data_ptr();
  362. params.oaccum_ptr = out_accum.data_ptr();
  363. params.oaccum_row_stride = out_accum.stride(-2);
  364. params.oaccum_head_stride = out_accum.stride(-3);
  365. params.oaccum_batch_stride = out_accum.stride(-4);
  366. params.oaccum_split_stride = out_accum.stride(0);
  367. }
  368. TORCH_CHECK(params.num_splits <= 128, "num_splits > 128 not supported");
  369. }
  370. return std::make_tuple(softmax_lse_accum, out_accum);
  371. }
  372. void run_mha_fwd(Flash_fwd_params &params, cudaStream_t stream, bool force_split_kernel=false) {
  373. int dtype = 1;
  374. if (params.is_bf16) { dtype = 2; }
  375. else if (params.is_e4m3) { dtype = 3; }
  376. PREC_SWITCH(dtype, Element, [&] {
  377. HEADDIM_SWITCH(params.d, kHeadSize, [&] {
  378. if(!params.use_gqa_packing) {
  379. run_mha_fwd_<Element, kHeadSize>(params, stream);
  380. } else {
  381. QUERYHEAD_SWITCH(params.h_h_k_ratio, kBlockH, [&] {
  382. run_mha_fwd_gqa_<Element, kHeadSize, kBlockH>(params, stream);
  383. });
  384. }
  385. });
  386. });
  387. #if 0
  388. if (!params.is_e4m3) {
  389. if (params.is_bf16) {
  390. if (params.d == 64) {
  391. run_mha_fwd_<cutlass::bfloat16_t, 64>(params, stream);
  392. } else if (params.d == 128) {
  393. run_mha_fwd_<cutlass::bfloat16_t, 128>(params, stream);
  394. } else {
  395. run_mha_fwd_<cutlass::bfloat16_t, 256>(params, stream);
  396. }
  397. } else {
  398. if (params.d == 64) {
  399. run_mha_fwd_<cutlass::half_t, 64>(params, stream);
  400. } else if (params.d == 128) {
  401. run_mha_fwd_<cutlass::half_t, 128>(params, stream);
  402. } else {
  403. run_mha_fwd_<cutlass::half_t, 256>(params, stream);
  404. }
  405. }
  406. } else {
  407. if (params.d == 64) {
  408. run_mha_fwd_<cutlass::float_e4m3_t, 64>(params, stream);
  409. } else if (params.d == 128) {
  410. run_mha_fwd_<cutlass::float_e4m3_t, 128>(params, stream);
  411. } else if (params.d == 256) {
  412. run_mha_fwd_<cutlass::float_e4m3_t, 256>(params, stream);
  413. }
  414. }
  415. #endif
  416. }
  417. std::vector<at::Tensor>
  418. mha_fwd(at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  419. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  420. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  421. c10::optional<at::Tensor> &out_, // batch_size x seqlen_q x num_heads x head_size
  422. const float softmax_scale,
  423. c10::optional<at::Tensor> &descale_q_, // 1
  424. c10::optional<at::Tensor> &descale_k_, // 1
  425. c10::optional<at::Tensor> &descale_v_, // 1
  426. bool is_causal,
  427. int window_size_left,
  428. int window_size_right,
  429. bool use_gqa_packing = false
  430. ) {
  431. auto dprops = at::cuda::getCurrentDeviceProperties();
  432. bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
  433. TORCH_CHECK(is_sm90, "FlashAttention-3 only supports Hopper GPUs or newer.");
  434. auto q_dtype = q.dtype();
  435. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
  436. "FlashAttention-3 only support fp16, bf16, or fp8 e4m3 data type");
  437. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  438. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  439. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  440. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  441. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  442. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  443. const auto sizes = q.sizes();
  444. const int batch_size = sizes[0];
  445. int seqlen_q = sizes[1];
  446. int num_heads = sizes[2];
  447. const int head_size_og = sizes[3];
  448. const int seqlen_k = k.size(1);
  449. const int num_heads_k = k.size(2);
  450. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  451. TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
  452. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  453. // Guard against mistaken setting of gqa flag
  454. if (num_heads == num_heads_k) { use_gqa_packing = false; }
  455. TORCH_CHECK(head_size_og == 64 || head_size_og == 128 || head_size_og == 256, "Only support head size 64, 128, and 256 for now");
  456. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
  457. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size_og);
  458. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size_og);
  459. at::Tensor q_padded, k_padded, v_padded;
  460. if (head_size_og % 8 != 0) {
  461. q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  462. k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  463. v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  464. } else {
  465. q_padded = q;
  466. k_padded = k;
  467. v_padded = v;
  468. }
  469. at::Tensor out;
  470. if (out_.has_value()) {
  471. out = out_.value();
  472. // TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  473. TORCH_CHECK(q_dtype == at::ScalarType::Float8_e4m3fn
  474. ? (out.dtype() == at::kBFloat16)
  475. : (out.dtype() == q_dtype),
  476. "Output must have the same dtype as input dtype if dtype is "
  477. "not fp8, or fp16 for fp8 input.");
  478. CHECK_DEVICE(out);
  479. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  480. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og);
  481. if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
  482. } else {
  483. if (q_dtype == at::ScalarType::Float8_e4m3fn)
  484. out = torch::empty_like(q_padded, at::kBFloat16);
  485. else
  486. out = torch::empty_like(q_padded);
  487. }
  488. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  489. const int head_size = round_multiple(head_size_og, 8);
  490. const int head_size_rounded = round_multiple(head_size, 32);
  491. const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
  492. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  493. if (is_causal) { window_size_right = 0; }
  494. // Otherwise the kernel will be launched from cuda:0 device
  495. // Cast to char to avoid compiler warning about narrowing
  496. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  497. auto opts = q.options();
  498. auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  499. at::Tensor p;
  500. Flash_fwd_params params;
  501. set_params_fprop(params,
  502. batch_size, batch_size,
  503. seqlen_q, seqlen_k,
  504. seqlen_q_rounded, seqlen_k_rounded,
  505. num_heads, num_heads_k,
  506. head_size, head_size_rounded,
  507. q_padded, k_padded, v_padded, out,
  508. /*cu_seqlens_q_d=*/nullptr,
  509. /*cu_seqlens_k_d=*/nullptr,
  510. /*seqused_q=*/nullptr,
  511. /*seqused_k=*/nullptr,
  512. nullptr,
  513. softmax_lse.data_ptr(),
  514. /*p_dropout=*/0.f,
  515. softmax_scale,
  516. /*window_size_left=*/window_size_left,
  517. /*window_size_right=*/window_size_right);
  518. auto tile_count_semaphore = is_causal || params.is_local
  519. ? torch::zeros({1}, opts.dtype(torch::kInt32)) : torch::empty({1}, opts.dtype(torch::kInt32));
  520. params.tile_count_semaphore = tile_count_semaphore.data_ptr<int>();
  521. at::Tensor descale_q, descale_k, descale_v;
  522. if(q_dtype == at::ScalarType::Float8_e4m3fn) {
  523. if (descale_q_.has_value()) {
  524. descale_q = descale_q_.value();
  525. CHECK_DEVICE(descale_q);
  526. CHECK_SHAPE(descale_q, 1);
  527. } else { descale_q = torch::ones({1}, opts.dtype(at::kFloat)); }
  528. if (descale_k_.has_value()) {
  529. descale_k = descale_k_.value();
  530. CHECK_DEVICE(descale_k);
  531. CHECK_SHAPE(descale_k, 1);
  532. } else { descale_k = torch::ones({1}, opts.dtype(at::kFloat)); }
  533. if (descale_v_.has_value()) {
  534. descale_v = descale_v_.value();
  535. CHECK_DEVICE(descale_v);
  536. CHECK_SHAPE(descale_v, 1);
  537. } else { descale_v = torch::ones({1}, opts.dtype(at::kFloat)); }
  538. params.descale_q_ptr = descale_q.data_ptr<float>();
  539. params.descale_k_ptr = descale_k.data_ptr<float>();
  540. params.descale_v_ptr = descale_v.data_ptr<float>();
  541. } else {
  542. params.descale_q_ptr = nullptr;
  543. params.descale_k_ptr = nullptr;
  544. params.descale_v_ptr = nullptr;
  545. }
  546. params.use_gqa_packing = use_gqa_packing;
  547. if (seqlen_k > 0) {
  548. auto stream = at::cuda::getCurrentCUDAStream().stream();
  549. run_mha_fwd(params, stream);
  550. } else {
  551. // If seqlen_k == 0, then we have an empty tensor. We need to set the output to 0.
  552. out.zero_();
  553. softmax_lse.fill_(std::numeric_limits<float>::infinity());
  554. }
  555. at::Tensor out_padded = out;
  556. if (head_size_og % 8 != 0) {
  557. out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  558. if (out_.has_value()) { out_.value().copy_(out); }
  559. }
  560. return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p};
  561. }
  562. std::vector<at::Tensor>
  563. mha_varlen_fwd(at::Tensor &q, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
  564. 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.
  565. 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.
  566. c10::optional<at::Tensor> &out_, // total_q x num_heads x head_size, total_k := \sum_{i=0}^{b} s_i
  567. const at::Tensor &cu_seqlens_q, // b+1
  568. const at::Tensor &cu_seqlens_k, // b+1
  569. c10::optional<at::Tensor> &seqused_q, // b. If given, only this many elements of each batch element's queries and outputs are used.
  570. c10::optional<at::Tensor> &seqused_k, // b. If given, only this many elements of each batch element's keys are used.
  571. int max_seqlen_q,
  572. const int max_seqlen_k,
  573. const float softmax_scale,
  574. bool is_causal,
  575. int window_size_left,
  576. int window_size_right) {
  577. auto dprops = at::cuda::getCurrentDeviceProperties();
  578. bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
  579. TORCH_CHECK(is_sm90, "FlashAttention only supports Hopper GPUs or newer.");
  580. auto q_dtype = q.dtype();
  581. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  582. "FlashAttention only support fp16 and bf16 data type");
  583. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  584. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  585. TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
  586. TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");
  587. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  588. CHECK_DEVICE(cu_seqlens_q);
  589. CHECK_DEVICE(cu_seqlens_k);
  590. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  591. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  592. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  593. CHECK_CONTIGUOUS(cu_seqlens_q);
  594. CHECK_CONTIGUOUS(cu_seqlens_k);
  595. const auto sizes = q.sizes();
  596. const int batch_size = cu_seqlens_q.numel() - 1;
  597. int num_heads = sizes[1];
  598. const int head_size_og = sizes[2];
  599. const int num_heads_k = k.size(1);
  600. void *cu_seqlens_q_d = cu_seqlens_q.data_ptr();
  601. const int total_q = q.sizes()[0];
  602. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  603. TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
  604. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  605. CHECK_SHAPE(q, total_q, num_heads, head_size_og);
  606. const int total_k = k.size(0);
  607. CHECK_SHAPE(k, total_k, num_heads_k, head_size_og);
  608. CHECK_SHAPE(v, total_k, num_heads_k, head_size_og);
  609. CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
  610. if (seqused_q.has_value()){
  611. auto seqused_q_ = seqused_q.value();
  612. TORCH_CHECK(seqused_q_.dtype() == torch::kInt32, "seqused_q must have dtype int32");
  613. TORCH_CHECK(seqused_q_.is_cuda(), "seqused_q must be on CUDA device");
  614. TORCH_CHECK(seqused_q_.is_contiguous(), "seqused_q must be contiguous");
  615. CHECK_SHAPE(seqused_q_, batch_size);
  616. }
  617. CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
  618. if (seqused_k.has_value()){
  619. auto seqused_k_ = seqused_k.value();
  620. TORCH_CHECK(seqused_k_.dtype() == torch::kInt32, "seqused_k must have dtype int32");
  621. TORCH_CHECK(seqused_k_.is_cuda(), "seqused_k must be on CUDA device");
  622. TORCH_CHECK(seqused_k_.is_contiguous(), "seqused_k must be contiguous");
  623. CHECK_SHAPE(seqused_k_, batch_size);
  624. }
  625. at::Tensor q_padded, k_padded, v_padded;
  626. if (head_size_og % 8 != 0) {
  627. q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  628. k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  629. v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  630. } else {
  631. q_padded = q;
  632. k_padded = k;
  633. v_padded = v;
  634. }
  635. at::Tensor out;
  636. if (out_.has_value()) {
  637. out = out_.value();
  638. TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  639. CHECK_DEVICE(out);
  640. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  641. CHECK_SHAPE(out, sizes[0], sizes[1], head_size_og);
  642. if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
  643. } else {
  644. out = torch::empty_like(q_padded);
  645. }
  646. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  647. const int head_size = round_multiple(head_size_og, 8);
  648. const int head_size_rounded = round_multiple(head_size, 32);
  649. const int seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
  650. const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
  651. if (is_causal) { window_size_right = 0; }
  652. // Otherwise the kernel will be launched from cuda:0 device
  653. // Cast to char to avoid compiler warning about narrowing
  654. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  655. auto opts = q.options();
  656. auto softmax_lse = torch::empty({num_heads, total_q}, opts.dtype(at::kFloat));
  657. Flash_fwd_params params;
  658. set_params_fprop(params,
  659. batch_size, batch_size,
  660. max_seqlen_q, max_seqlen_k,
  661. seqlen_q_rounded, seqlen_k_rounded,
  662. num_heads, num_heads_k,
  663. head_size, head_size_rounded,
  664. q_padded, k_padded, v_padded, out,
  665. cu_seqlens_q_d,
  666. cu_seqlens_k.data_ptr(),
  667. seqused_q.has_value() ? seqused_q.value().data_ptr() : nullptr,
  668. seqused_k.has_value() ? seqused_k.value().data_ptr() : nullptr,
  669. /*p_d=*/nullptr,
  670. softmax_lse.data_ptr(),
  671. /*p_dropout=*/0.f,
  672. softmax_scale,
  673. window_size_left,
  674. window_size_right,
  675. /*seqlenq_ngroups_swapped=*/false,
  676. /*unpadded_lse=*/true);
  677. params.total_q = total_q;
  678. params.total_k = total_k;
  679. if (max_seqlen_k > 0) {
  680. auto stream = at::cuda::getCurrentCUDAStream().stream();
  681. run_mha_fwd(params, stream);
  682. } else {
  683. // If seqlen_k == 0, then we have an empty tensor. We need to set the output to 0.
  684. out.zero_();
  685. softmax_lse.fill_(std::numeric_limits<float>::infinity());
  686. }
  687. at::Tensor out_padded = out;
  688. if (head_size_og % 8 != 0) {
  689. out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  690. if (out_.has_value()) { out_.value().copy_(out); }
  691. }
  692. return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse};
  693. }
  694. void run_mha_bwd(Flash_bwd_params &params, cudaStream_t stream) {
  695. // FP16_SWITCH(!params.is_bf16, [&] {
  696. // HEADDIM_SWITCH(params.d, [&] {
  697. // run_mha_bwd_<elem_type, kHeadDim>(params, stream);
  698. // });
  699. // });
  700. if (!params.is_bf16) {
  701. if (params.d <= 64) {
  702. run_mha_bwd_<cutlass::half_t, 64>(params, stream);
  703. } else if (params.d <= 96) {
  704. run_mha_bwd_<cutlass::half_t, 96>(params, stream);
  705. } else {
  706. run_mha_bwd_<cutlass::half_t, 128>(params, stream);
  707. }
  708. } else {
  709. if (params.d <= 64) {
  710. run_mha_bwd_<cutlass::bfloat16_t, 64>(params, stream);
  711. } else if (params.d <= 96) {
  712. run_mha_bwd_<cutlass::bfloat16_t, 96>(params, stream);
  713. } else {
  714. run_mha_bwd_<cutlass::bfloat16_t, 128>(params, stream);
  715. }
  716. }
  717. }
  718. std::vector<at::Tensor>
  719. mha_bwd(const at::Tensor &dout, // batch_size x seqlen_q x num_heads, x head_size_og
  720. const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  721. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  722. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  723. const at::Tensor &out, // batch_size x seqlen_q x num_heads x head_size
  724. const at::Tensor &softmax_lse, // b x h x seqlen_q
  725. c10::optional<at::Tensor> &dq_, // batch_size x seqlen_q x num_heads x head_size
  726. c10::optional<at::Tensor> &dk_, // batch_size x seqlen_k x num_heads_k x head_size
  727. c10::optional<at::Tensor> &dv_, // batch_size x seqlen_k x num_heads_k x head_size
  728. const float softmax_scale,
  729. const bool is_causal,
  730. int window_size_left,
  731. int window_size_right,
  732. const bool deterministic) {
  733. #ifdef FLASHATTENTION_DISABLE_BACKWARD
  734. TORCH_CHECK(false, "This flash attention build does not support backward.");
  735. #endif
  736. auto dprops = at::cuda::getCurrentDeviceProperties();
  737. bool is_sm9x = dprops->major == 9 && dprops->minor >= 0;
  738. TORCH_CHECK(is_sm9x, "FlashAttentionHopper only supports Hopper GPUs or newer.");
  739. auto stream = at::cuda::getCurrentCUDAStream().stream();
  740. auto q_dtype = q.dtype();
  741. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  742. "FlashAttention only support fp16 and bf16 data type");
  743. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  744. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  745. TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
  746. TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
  747. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  748. CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
  749. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  750. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  751. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  752. TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
  753. TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
  754. const auto sizes = q.sizes();
  755. const int batch_size = sizes[0];
  756. const int seqlen_q = sizes[1];
  757. const int num_heads = sizes[2];
  758. const int head_size_og = dout.size(3);
  759. const int head_size = sizes[3];
  760. const int seqlen_k = k.size(1);
  761. const int num_heads_k = k.size(2);
  762. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  763. TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
  764. TORCH_CHECK(head_size <= 128, "FlashAttention backward only supports head dimension at most 128");
  765. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  766. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  767. const int head_size_rounded = head_size <= 64 ? 64 : round_multiple(head_size, 32);
  768. // This should match the kernel configs
  769. const int kBlockM = head_size <= 64 ? 128 : (head_size < 256 ? 64 : 32);
  770. const int seqlen_q_rounded = round_multiple(seqlen_q, kBlockM);
  771. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  772. TORCH_CHECK(head_size == round_multiple(head_size_og, 8), "head_size must be head_size_og rounded to a multiple of 8");
  773. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size);
  774. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size);
  775. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size);
  776. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size);
  777. CHECK_SHAPE(dout, batch_size, seqlen_q, num_heads, head_size_og);
  778. at::Tensor dq, dk, dv;
  779. if (dq_.has_value()) {
  780. dq = dq_.value();
  781. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  782. CHECK_DEVICE(dq);
  783. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  784. CHECK_SHAPE(dq, batch_size, seqlen_q, num_heads, head_size);
  785. } else {
  786. dq = torch::empty_like(q);
  787. }
  788. if (dk_.has_value()) {
  789. dk = dk_.value();
  790. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  791. CHECK_DEVICE(dk);
  792. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  793. CHECK_SHAPE(dk, batch_size, seqlen_k, num_heads_k, head_size);
  794. } else {
  795. dk = torch::empty_like(k);
  796. }
  797. if (dv_.has_value()) {
  798. dv = dv_.value();
  799. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  800. CHECK_DEVICE(dv);
  801. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  802. CHECK_SHAPE(dv, batch_size, seqlen_k, num_heads_k, head_size);
  803. } else {
  804. dv = torch::empty_like(v);
  805. }
  806. at::Tensor dout_padded;
  807. if (head_size_og % 8 != 0) {
  808. dout_padded = torch::nn::functional::pad(dout, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  809. } else {
  810. dout_padded = dout;
  811. }
  812. // Otherwise the kernel will be launched from cuda:0 device
  813. // Cast to char to avoid compiler warning about narrowing
  814. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  815. auto opts = q.options();
  816. // Need softmax_d to have seqlen_q_rounded since we want its address to be aligned by 16/8 bytes for TMA / LDG.64
  817. auto softmax_d = torch::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
  818. auto softmax_lse_log2 = torch::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
  819. at::Tensor dq_accum;
  820. at::Tensor dk_accum, dv_accum;
  821. dq_accum = torch::empty({batch_size, num_heads, seqlen_q_rounded, head_size_rounded}, opts.dtype(at::kFloat));
  822. // dk_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  823. // dv_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  824. at::Tensor dk_expanded, dv_expanded;
  825. if (num_heads_k != num_heads) { // MQA / GQA
  826. dk_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  827. dv_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  828. } else {
  829. dk_expanded = dk;
  830. dv_expanded = dv;
  831. }
  832. if (is_causal) { window_size_right = 0; }
  833. Flash_bwd_params params;
  834. set_params_dgrad(params,
  835. batch_size,
  836. seqlen_q, seqlen_k,
  837. seqlen_q_rounded, seqlen_k_rounded,
  838. num_heads, num_heads_k,
  839. head_size, head_size_rounded,
  840. q, k, v, out,
  841. dout_padded, dq, dk_expanded, dv_expanded,
  842. /*cu_seqlens_q_d=*/nullptr,
  843. /*cu_seqlens_k_d=*/nullptr,
  844. /*seqused_q=*/nullptr,
  845. /*seqused_k=*/nullptr,
  846. dq_accum.data_ptr(),
  847. // loop ? dk_accum.data_ptr() : nullptr,
  848. // loop ? dv_accum.data_ptr() : nullptr,
  849. nullptr,
  850. nullptr,
  851. softmax_lse.data_ptr(),
  852. softmax_d.data_ptr(),
  853. /*p_dropout=*/0.f,
  854. softmax_scale,
  855. /*window_size_left=*/window_size_left,
  856. /*window_size_right=*/window_size_right,
  857. deterministic);
  858. params.softmax_lse_log2_ptr = softmax_lse_log2.data_ptr();
  859. // Will be zero'ed out in the backward preprocess kernel
  860. at::Tensor dq_semaphore = torch::empty({(seqlen_q + kBlockM - 1) / kBlockM, batch_size, num_heads}, opts.dtype(torch::kInt32));
  861. params.dq_semaphore = dq_semaphore.data_ptr<int>();
  862. // printf("dq_semaphore: %p, [%d, %d, %d]\n", params.dq_semaphore, (seqlen_q + 64 - 1) / 64, batch_size, num_heads);
  863. if (seqlen_q > 0) {
  864. run_mha_bwd(params, stream);
  865. } else {
  866. // If seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  867. dk_expanded.zero_();
  868. dv_expanded.zero_();
  869. softmax_d.zero_();
  870. }
  871. // For MQA/GQA we need to sum dK and dV across the groups
  872. if (num_heads_k != num_heads) {
  873. at::sum_out(dk, at::reshape(dk_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  874. at::sum_out(dv, at::reshape(dv_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  875. }
  876. if (head_size_og % 8 != 0) {
  877. dq = dq.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  878. dk = dk.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  879. dv = dv.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  880. }
  881. return { dq, dk, dv, softmax_d, dq_accum};
  882. }
  883. std::vector<at::Tensor>
  884. mha_varlen_bwd(const at::Tensor &dout, // batch_size x seqlen_q x num_heads, x head_size_og
  885. const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  886. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  887. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  888. const at::Tensor &out, // batch_size x seqlen_q x num_heads x head_size
  889. const at::Tensor &softmax_lse, // b x h x seqlen_q
  890. c10::optional<at::Tensor> &dq_, // batch_size x seqlen_q x num_heads x head_size
  891. c10::optional<at::Tensor> &dk_, // batch_size x seqlen_k x num_heads_k x head_size
  892. c10::optional<at::Tensor> &dv_, // batch_size x seqlen_k x num_heads_k x head_size
  893. const at::Tensor &cu_seqlens_q, // b+1
  894. const at::Tensor &cu_seqlens_k, // b+1
  895. c10::optional<at::Tensor> &seqused_q, // b. If given, only this many elements of each batch element's queries and outputs are used.
  896. c10::optional<at::Tensor> &seqused_k, // b. If given, only this many elements of each batch element's keys are used.
  897. const int max_seqlen_q,
  898. const int max_seqlen_k, // max sequence length to choose the kernel
  899. const float softmax_scale,
  900. const bool is_causal,
  901. int window_size_left,
  902. int window_size_right,
  903. const bool deterministic) {
  904. #ifdef FLASHATTENTION_DISABLE_BACKWARD
  905. TORCH_CHECK(false, "This flash attention build does not support backward.");
  906. #endif
  907. auto dprops = at::cuda::getCurrentDeviceProperties();
  908. bool is_sm9x = dprops->major == 9 && dprops->minor >= 0;
  909. TORCH_CHECK(is_sm9x, "FlashAttentionHopper only supports Hopper GPUs or newer.");
  910. auto stream = at::cuda::getCurrentCUDAStream().stream();
  911. auto q_dtype = q.dtype();
  912. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  913. "FlashAttention only support fp16 and bf16 data type");
  914. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  915. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  916. TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
  917. TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
  918. TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
  919. TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");
  920. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  921. CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
  922. CHECK_DEVICE(cu_seqlens_q); CHECK_DEVICE(cu_seqlens_k);
  923. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  924. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  925. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  926. TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
  927. TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
  928. CHECK_CONTIGUOUS(cu_seqlens_q);
  929. CHECK_CONTIGUOUS(cu_seqlens_k);
  930. const auto sizes = q.sizes();
  931. const int total_q = sizes[0];
  932. const int batch_size = cu_seqlens_q.numel() - 1;
  933. const int num_heads = sizes[1];
  934. const int head_size_og = dout.size(2);
  935. const int head_size = sizes[2];
  936. const int total_k = k.size(0);
  937. const int num_heads_k = k.size(1);
  938. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  939. TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
  940. TORCH_CHECK(head_size <= 128, "FlashAttention backward only supports head dimension at most 128");
  941. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  942. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  943. const int head_size_rounded = head_size <= 64 ? 64 : round_multiple(head_size, 32);
  944. // This should match the kernel configs
  945. const int kBlockM = head_size <= 64 ? 128 : (head_size < 256 ? 64 : 32);
  946. const int seqlen_q_rounded = round_multiple(max_seqlen_q, kBlockM);
  947. const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
  948. int const total_q_padded_rounded = round_multiple(total_q + batch_size * 128, 128);
  949. TORCH_CHECK(head_size == round_multiple(head_size_og, 8), "head_size must be head_size_og rounded to a multiple of 8");
  950. CHECK_SHAPE(q, total_q, num_heads, head_size_og);
  951. CHECK_SHAPE(k, total_k, num_heads_k, head_size_og);
  952. CHECK_SHAPE(v, total_k, num_heads_k, head_size_og);
  953. CHECK_SHAPE(out, total_q, num_heads, head_size);
  954. CHECK_SHAPE(dout, total_q, num_heads, head_size_og);
  955. CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
  956. if (seqused_q.has_value()){
  957. auto seqused_q_ = seqused_q.value();
  958. TORCH_CHECK(seqused_q_.dtype() == torch::kInt32, "seqused_q must have dtype int32");
  959. TORCH_CHECK(seqused_q_.is_cuda(), "seqused_q must be on CUDA device");
  960. TORCH_CHECK(seqused_q_.is_contiguous(), "seqused_q must be contiguous");
  961. CHECK_SHAPE(seqused_q_, batch_size);
  962. }
  963. CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
  964. if (seqused_k.has_value()){
  965. auto seqused_k_ = seqused_k.value();
  966. TORCH_CHECK(seqused_k_.dtype() == torch::kInt32, "seqused_k must have dtype int32");
  967. TORCH_CHECK(seqused_k_.is_cuda(), "seqused_k must be on CUDA device");
  968. TORCH_CHECK(seqused_k_.is_contiguous(), "seqused_k must be contiguous");
  969. CHECK_SHAPE(seqused_k_, batch_size);
  970. }
  971. at::Tensor dq, dk, dv;
  972. if (dq_.has_value()) {
  973. dq = dq_.value();
  974. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  975. CHECK_DEVICE(dq);
  976. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  977. CHECK_SHAPE(dq, total_q, num_heads, head_size);
  978. } else {
  979. dq = torch::empty_like(q);
  980. }
  981. if (dk_.has_value()) {
  982. dk = dk_.value();
  983. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  984. CHECK_DEVICE(dk);
  985. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  986. CHECK_SHAPE(dk, total_k, num_heads_k, head_size);
  987. } else {
  988. dk = torch::empty_like(k);
  989. }
  990. if (dv_.has_value()) {
  991. dv = dv_.value();
  992. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  993. CHECK_DEVICE(dv);
  994. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  995. CHECK_SHAPE(dv, total_k, num_heads_k, head_size);
  996. } else {
  997. dv = torch::empty_like(v);
  998. }
  999. at::Tensor dout_padded;
  1000. if (head_size_og % 8 != 0) {
  1001. dout_padded = torch::nn::functional::pad(dout, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1002. } else {
  1003. dout_padded = dout;
  1004. }
  1005. if (is_causal) { window_size_right = 0; }
  1006. // Otherwise the kernel will be launched from cuda:0 device
  1007. // Cast to char to avoid compiler warning about narrowing
  1008. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  1009. auto opts = q.options();
  1010. // Need softmax_d to have total_q_padded_rounded since we want its address to be aligned by 16/8 bytes for TMA / LDG.64
  1011. auto softmax_d = torch::empty({num_heads, total_q_padded_rounded}, opts.dtype(at::kFloat));
  1012. auto softmax_lse_log2 = torch::empty({num_heads, total_q_padded_rounded}, opts.dtype(at::kFloat));
  1013. at::Tensor dq_accum;
  1014. at::Tensor dk_accum, dv_accum;
  1015. dq_accum = torch::empty({num_heads, total_q_padded_rounded, head_size_rounded}, opts.dtype(at::kFloat));
  1016. // dk_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  1017. // dv_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  1018. at::Tensor dk_expanded, dv_expanded;
  1019. if (num_heads_k != num_heads) { // MQA / GQA
  1020. dk_expanded = torch::empty({total_k, num_heads, head_size}, opts);
  1021. dv_expanded = torch::empty({total_k, num_heads, head_size}, opts);
  1022. } else {
  1023. dk_expanded = dk;
  1024. dv_expanded = dv;
  1025. }
  1026. Flash_bwd_params params;
  1027. set_params_dgrad(params,
  1028. batch_size,
  1029. max_seqlen_q, max_seqlen_k,
  1030. seqlen_q_rounded, seqlen_k_rounded,
  1031. num_heads, num_heads_k,
  1032. head_size, head_size_rounded,
  1033. q, k, v, out,
  1034. dout_padded, dq, dk_expanded, dv_expanded,
  1035. cu_seqlens_q.data_ptr(),
  1036. cu_seqlens_k.data_ptr(),
  1037. seqused_q.has_value() ? seqused_q.value().data_ptr() : nullptr,
  1038. seqused_k.has_value() ? seqused_k.value().data_ptr() : nullptr,
  1039. dq_accum.data_ptr(),
  1040. // loop ? dk_accum.data_ptr() : nullptr,
  1041. // loop ? dv_accum.data_ptr() : nullptr,
  1042. nullptr,
  1043. nullptr,
  1044. softmax_lse.data_ptr(),
  1045. softmax_d.data_ptr(),
  1046. /*p_dropout=*/0.f,
  1047. softmax_scale,
  1048. /*window_size_left=*/window_size_left,
  1049. /*window_size_right=*/window_size_right,
  1050. deterministic);
  1051. params.total_q = total_q;
  1052. params.total_k = total_k;
  1053. params.softmax_lse_log2_ptr = softmax_lse_log2.data_ptr();
  1054. // Will be zero'ed out in the backward preprocess kernel
  1055. at::Tensor dq_semaphore = torch::empty({(max_seqlen_q + kBlockM - 1) / kBlockM, batch_size, num_heads}, opts.dtype(torch::kInt32));
  1056. params.dq_semaphore = dq_semaphore.data_ptr<int>();
  1057. if (max_seqlen_q > 0) {
  1058. run_mha_bwd(params, stream);
  1059. } else {
  1060. // If max_seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  1061. dk_expanded.zero_();
  1062. dv_expanded.zero_();
  1063. softmax_d.zero_();
  1064. }
  1065. // For MQA/GQA we need to sum dK and dV across the groups
  1066. if (num_heads_k != num_heads) {
  1067. at::sum_out(dk, at::reshape(dk_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
  1068. at::sum_out(dv, at::reshape(dv_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
  1069. }
  1070. if (head_size_og % 8 != 0) {
  1071. dq = dq.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1072. dk = dk.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1073. dv = dv.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1074. }
  1075. return { dq, dk, dv, softmax_d, dq_accum, softmax_lse_log2 };
  1076. }
  1077. std::vector<at::Tensor>
  1078. mha_fwd_kvcache(at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  1079. 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.
  1080. 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.
  1081. c10::optional<const at::Tensor> &k_, // batch_size x seqlen_knew x num_heads_k x head_size
  1082. c10::optional<const at::Tensor> &v_, // batch_size x seqlen_knew x num_heads_k x head_size
  1083. c10::optional<const at::Tensor> &seqlens_k_, // batch_size
  1084. c10::optional<const at::Tensor> &rotary_cos_, // seqlen_ro x (rotary_dim / 2)
  1085. c10::optional<const at::Tensor> &rotary_sin_, // seqlen_ro x (rotary_dim / 2)
  1086. c10::optional<const at::Tensor> &cache_batch_idx_, // indices to index into the KV cache
  1087. c10::optional<const at::Tensor> &leftpad_k_, // batch_size
  1088. c10::optional<at::Tensor> &block_table_, // batch_size x max_num_blocks_per_seq
  1089. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
  1090. c10::optional<at::Tensor> &out_, // batch_size x seqlen_q x num_heads x head_size
  1091. const float softmax_scale,
  1092. c10::optional<at::Tensor> &descale_q_, // 1
  1093. c10::optional<at::Tensor> &descale_k_, // 1
  1094. c10::optional<at::Tensor> &descale_v_, // 1
  1095. bool is_causal,
  1096. int window_size_left,
  1097. int window_size_right,
  1098. const float softcap,
  1099. bool is_rotary_interleaved, // if true, rotary combines indices 0 & 1, else indices 0 & rotary_dim / 2
  1100. int num_splits,
  1101. int max_seqlen_k_hint,
  1102. bool use_gqa_packing
  1103. ) {
  1104. auto dprops = at::cuda::getCurrentDeviceProperties();
  1105. // bool is_sm75 = dprops->major == 7 && dprops->minor == 5;
  1106. // bool is_sm8x = dprops->major == 8 && dprops->minor >= 0;
  1107. bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
  1108. TORCH_CHECK(is_sm90, "FlashAttention-3 only supports Hopper GPUs or newer.");
  1109. auto q_dtype = q.dtype();
  1110. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
  1111. "FlashAttention-3 only support fp16, bf16, or fp8 e4m3 data type");
  1112. TORCH_CHECK(kcache.dtype() == q_dtype, "query and key must have the same dtype");
  1113. TORCH_CHECK(vcache.dtype() == q_dtype, "query and value must have the same dtype");
  1114. CHECK_DEVICE(q); CHECK_DEVICE(kcache); CHECK_DEVICE(vcache);
  1115. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1116. TORCH_CHECK(kcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1117. TORCH_CHECK(vcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1118. at::Tensor block_table;
  1119. const bool paged_KV = block_table_.has_value();
  1120. if (paged_KV) {
  1121. TORCH_CHECK(!cache_batch_idx_.has_value(), "Paged KVcache does not support cache_batch_idx");
  1122. block_table = block_table_.value();
  1123. CHECK_DEVICE(block_table);
  1124. TORCH_CHECK(block_table.dtype() == torch::kInt32, "block_table must have dtype torch.int32");
  1125. TORCH_CHECK(block_table.stride(-1) == 1, "block_table must have contiguous last dimension");
  1126. }
  1127. const auto sizes = q.sizes();
  1128. const int batch_size = sizes[0];
  1129. int seqlen_q = sizes[1];
  1130. int num_heads = sizes[2];
  1131. const int head_size_og = sizes[3];
  1132. const int max_num_blocks_per_seq = !paged_KV ? 0 : block_table.size(1);
  1133. const int num_blocks = !paged_KV ? 0 : kcache.size(0);
  1134. const int page_block_size = !paged_KV ? 1 : kcache.size(1);
  1135. TORCH_CHECK(!paged_KV || page_block_size % 256 == 0, "Paged KV cache block size must be divisible by 256");
  1136. const int seqlen_k = !paged_KV ? kcache.size(1) : max_num_blocks_per_seq * page_block_size;
  1137. const int num_heads_k = kcache.size(2);
  1138. const int batch_size_c = !paged_KV ? kcache.size(0) : batch_size;
  1139. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  1140. TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
  1141. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  1142. // Guard against mistaken setting of gqa flag
  1143. if (num_heads == num_heads_k) { use_gqa_packing = false; }
  1144. // causal=true is the same as causal=false in this case
  1145. if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }
  1146. if (is_causal) { window_size_right = 0; }
  1147. // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
  1148. // H/t Daniel Haziza
  1149. const int seqlenq_ngroups_swapped =
  1150. seqlen_q == 1 && num_heads > num_heads_k && window_size_left < 0 &&
  1151. window_size_right < 0 && head_size_og % 8 == 0 &&
  1152. !alibi_slopes_.has_value() && !use_gqa_packing;
  1153. if (seqlenq_ngroups_swapped) {
  1154. const int ngroups = num_heads / num_heads_k;
  1155. q = q.reshape({batch_size, num_heads_k, ngroups, head_size_og}).transpose(1, 2);
  1156. seqlen_q = ngroups;
  1157. num_heads = num_heads_k;
  1158. }
  1159. if (window_size_left >= seqlen_k) { window_size_left = -1; }
  1160. if (window_size_right >= seqlen_k) { window_size_right = -1; }
  1161. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
  1162. if (!paged_KV) {
  1163. CHECK_SHAPE(kcache, batch_size_c, seqlen_k, num_heads_k, head_size_og);
  1164. CHECK_SHAPE(vcache, batch_size_c, seqlen_k, num_heads_k, head_size_og);
  1165. } else {
  1166. CHECK_SHAPE(kcache, num_blocks, page_block_size, num_heads_k, head_size_og);
  1167. CHECK_SHAPE(vcache, num_blocks, page_block_size, num_heads_k, head_size_og);
  1168. CHECK_SHAPE(block_table, batch_size, max_num_blocks_per_seq);
  1169. }
  1170. at::Tensor q_padded, kcache_padded, vcache_padded;
  1171. if (head_size_og % 8 != 0) {
  1172. q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1173. kcache_padded = torch::nn::functional::pad(kcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1174. vcache_padded = torch::nn::functional::pad(vcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1175. } else {
  1176. q_padded = q;
  1177. kcache_padded = kcache;
  1178. vcache_padded = vcache;
  1179. }
  1180. at::Tensor out;
  1181. if (out_.has_value()) {
  1182. out = out_.value();
  1183. // TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  1184. TORCH_CHECK(q_dtype == at::ScalarType::Float8_e4m3fn
  1185. ? (out.dtype() == at::kBFloat16)
  1186. : (out.dtype() == q_dtype),
  1187. "Output must have the same dtype as input dtype if dtype is "
  1188. "not fp8, or fp16 for fp8 input.");
  1189. CHECK_DEVICE(out);
  1190. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  1191. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og);
  1192. if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
  1193. } else {
  1194. if (q_dtype == at::ScalarType::Float8_e4m3fn) {
  1195. out = torch::empty_like(q_padded, at::kBFloat16);
  1196. }
  1197. else
  1198. out = torch::empty_like(q_padded);
  1199. }
  1200. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  1201. const int head_size = round_multiple(head_size_og, 8);
  1202. const int head_size_rounded = head_size <= 192 ? round_multiple(head_size, 32) : 256;
  1203. const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
  1204. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  1205. // Otherwise the kernel will be launched from cuda:0 device
  1206. // Cast to char to avoid compiler warning about narrowing
  1207. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  1208. auto opts = q.options();
  1209. auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  1210. Flash_fwd_params params;
  1211. set_params_fprop(params,
  1212. batch_size, batch_size_c,
  1213. seqlen_q, seqlen_k,
  1214. seqlen_q_rounded, seqlen_k_rounded,
  1215. num_heads, num_heads_k,
  1216. head_size, head_size_rounded,
  1217. q_padded, kcache_padded, vcache_padded, out,
  1218. /*cu_seqlens_q_d=*/nullptr,
  1219. /*cu_seqlens_k_d=*/nullptr,
  1220. /*seqused_q=*/nullptr,
  1221. /*seqused_k=*/nullptr,
  1222. /*p_ptr=*/nullptr,
  1223. softmax_lse.data_ptr(),
  1224. /*p_dropout=*/0.f,
  1225. softmax_scale,
  1226. window_size_left,
  1227. window_size_right
  1228. );
  1229. at::Tensor descale_q, descale_k, descale_v;
  1230. if(q_dtype == at::ScalarType::Float8_e4m3fn) {
  1231. if (descale_q_.has_value()) {
  1232. descale_q = descale_q_.value();
  1233. CHECK_DEVICE(descale_q);
  1234. CHECK_SHAPE(descale_q, 1);
  1235. } else { descale_q = torch::ones({1}, opts.dtype(at::kFloat)); }
  1236. if (descale_k_.has_value()) {
  1237. descale_k = descale_k_.value();
  1238. CHECK_DEVICE(descale_k);
  1239. CHECK_SHAPE(descale_k, 1);
  1240. } else { descale_k = torch::ones({1}, opts.dtype(at::kFloat)); }
  1241. if (descale_v_.has_value()) {
  1242. descale_v = descale_v_.value();
  1243. CHECK_DEVICE(descale_v);
  1244. CHECK_SHAPE(descale_v, 1);
  1245. } else { descale_v = torch::ones({1}, opts.dtype(at::kFloat)); }
  1246. params.descale_q_ptr = descale_q.data_ptr<float>();
  1247. params.descale_k_ptr = descale_k.data_ptr<float>();
  1248. params.descale_v_ptr = descale_v.data_ptr<float>();
  1249. } else {
  1250. params.descale_q_ptr = nullptr;
  1251. params.descale_k_ptr = nullptr;
  1252. params.descale_v_ptr = nullptr;
  1253. }
  1254. params.is_kv_cache = true;
  1255. params.use_gqa_packing = use_gqa_packing;
  1256. at::Tensor k, v, k_padded, v_padded;
  1257. if (k_.has_value()) {
  1258. TORCH_CHECK(v_.has_value(), "If key is supplied, value must also be passed in");
  1259. TORCH_CHECK(seqlens_k_.has_value(), "If key is supplied, seqlens_k must also be passed in");
  1260. TORCH_CHECK(seqlen_q <= seqlen_k, "If key is supplied, it must have seqlen <= the seqlen of the KV cache");
  1261. k = k_.value();
  1262. v = v_.value();
  1263. TORCH_CHECK(k.dtype() == q_dtype, "Key must have the same dtype as query");
  1264. TORCH_CHECK(v.dtype() == q_dtype, "Value must have the same dtype as query");
  1265. CHECK_DEVICE(k); CHECK_DEVICE(v);
  1266. TORCH_CHECK(k.stride(-1) == 1, "Key tensor must have contiguous last dimension");
  1267. TORCH_CHECK(v.stride(-1) == 1, "Value tensor must have contiguous last dimension");
  1268. int seqlen_knew = k.size(1);
  1269. CHECK_SHAPE(k, batch_size, seqlen_knew, num_heads_k, head_size_og);
  1270. CHECK_SHAPE(v, batch_size, seqlen_knew, num_heads_k, head_size_og);
  1271. if (head_size_og % 8 != 0) {
  1272. k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1273. v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1274. } else {
  1275. k_padded = k;
  1276. v_padded = v;
  1277. }
  1278. params.seqlen_knew = seqlen_knew;
  1279. params.knew_ptr = k_padded.data_ptr();
  1280. params.vnew_ptr = v_padded.data_ptr();
  1281. // All stride are in elements, not bytes.
  1282. params.knew_batch_stride = k_padded.stride(0);
  1283. params.vnew_batch_stride = v_padded.stride(0);
  1284. params.knew_row_stride = k_padded.stride(-3);
  1285. params.vnew_row_stride = v_padded.stride(-3);
  1286. params.knew_head_stride = k_padded.stride(-2);
  1287. params.vnew_head_stride = v_padded.stride(-2);
  1288. }
  1289. if (seqlens_k_.has_value()) {
  1290. auto seqlens_k = seqlens_k_.value();
  1291. TORCH_CHECK(seqlens_k.dtype() == torch::kInt32, "seqlens_k must have dtype int32");
  1292. CHECK_DEVICE(seqlens_k);
  1293. CHECK_CONTIGUOUS(seqlens_k);
  1294. CHECK_SHAPE(seqlens_k, batch_size);
  1295. params.seqused_k = static_cast<int *>(seqlens_k.data_ptr());
  1296. }
  1297. if (leftpad_k_.has_value()) {
  1298. TORCH_CHECK(!paged_KV, "We don't support Paged KV and leftpad_k running at the same time yet");
  1299. auto leftpad_k = leftpad_k_.value();
  1300. TORCH_CHECK(leftpad_k.dtype() == torch::kInt32, "leftpad_k must have dtype int32");
  1301. CHECK_DEVICE(leftpad_k);
  1302. CHECK_CONTIGUOUS(leftpad_k);
  1303. CHECK_SHAPE(leftpad_k, batch_size);
  1304. TORCH_CHECK(false, "Left Padding K is not supported");
  1305. //params.leftpad_k = static_cast<int *>(leftpad_k.data_ptr());
  1306. }
  1307. if (rotary_cos_.has_value()) {
  1308. TORCH_CHECK(k_.has_value(), "If rotary cos/sin are provided, new key / value to be appended to KV cache must also be provided");
  1309. auto rotary_cos = rotary_cos_.value();
  1310. CHECK_DEVICE(rotary_cos);
  1311. params.rotary_dim = rotary_cos.size(1) * 2;
  1312. TORCH_CHECK(params.rotary_dim <= head_size, "rotary_dim must be <= headdim");
  1313. TORCH_CHECK(params.rotary_dim % 16 == 0, "Only rotary dimensions divisible by 16 are currently supported");
  1314. const int seqlen_ro = rotary_cos.size(0);
  1315. TORCH_CHECK(seqlen_ro >= seqlen_k, "cos/sin seqlen must be at least the seqlen of KV cache");
  1316. CHECK_SHAPE(rotary_cos, seqlen_ro, params.rotary_dim / 2);
  1317. CHECK_CONTIGUOUS(rotary_cos);
  1318. TORCH_CHECK(rotary_cos.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");
  1319. TORCH_CHECK(rotary_sin_.has_value(), "If rotary cos is provided, rotary sin must also be provided");
  1320. auto rotary_sin = rotary_sin_.value();
  1321. CHECK_DEVICE(rotary_sin);
  1322. CHECK_SHAPE(rotary_sin, seqlen_ro, params.rotary_dim / 2);
  1323. CHECK_CONTIGUOUS(rotary_sin);
  1324. TORCH_CHECK(rotary_sin.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");
  1325. params.rotary_cos_ptr = rotary_cos.data_ptr();
  1326. params.rotary_sin_ptr = rotary_sin.data_ptr();
  1327. params.is_rotary_interleaved = is_rotary_interleaved;
  1328. } else {
  1329. params.rotary_dim = 0;
  1330. }
  1331. if (cache_batch_idx_.has_value()) {
  1332. auto cache_batch_idx = cache_batch_idx_.value();
  1333. CHECK_DEVICE(cache_batch_idx);
  1334. CHECK_CONTIGUOUS(cache_batch_idx);
  1335. TORCH_CHECK(cache_batch_idx.scalar_type() == torch::kInt32, "cache_batch_idx must have dtype int32");
  1336. params.cache_batch_idx = reinterpret_cast<int *>(cache_batch_idx.data_ptr());
  1337. }
  1338. // Keep references to these tensors to extend their lifetime
  1339. at::Tensor softmax_lse_accum, out_accum;
  1340. std::tie(softmax_lse_accum, out_accum) = set_params_splitkv(
  1341. params, batch_size, num_heads, num_heads_k, head_size, max_seqlen_k_hint, seqlen_q,
  1342. head_size_rounded, /*dropout*/ 0.f, num_splits, dprops, use_gqa_packing, is_causal, opts);
  1343. auto tile_count_semaphore = is_causal || params.is_local || params.num_splits != 1
  1344. ? torch::zeros({1}, opts.dtype(torch::kInt32))
  1345. : torch::empty({1}, opts.dtype(torch::kInt32));
  1346. params.tile_count_semaphore = tile_count_semaphore.data_ptr<int>();
  1347. if (paged_KV) {
  1348. params.block_table = block_table.data_ptr<int>();
  1349. params.block_table_batch_stride = block_table.stride(0);
  1350. }
  1351. params.page_block_size = page_block_size;
  1352. TORCH_CHECK(!alibi_slopes_.has_value(), "Alibi Slopes are not supported yet");
  1353. //set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
  1354. auto stream = at::cuda::getCurrentCUDAStream().stream();
  1355. // Only split kernel supports appending to KV cache, or indexing to the cache with cache_batch_idx,
  1356. // or paged KV cache
  1357. //run_mha_fwd(params, stream, /*force_split_kernel=*/k_.has_value() || cache_batch_idx_.has_value() || paged_KV);
  1358. run_mha_fwd(params, stream);
  1359. if (head_size_og % 8 != 0) {
  1360. out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1361. if (out_.has_value()) { out_.value().copy_(out); }
  1362. if (k_.has_value()) {
  1363. // It's expensive to copy the KV cache here for the case where head size not divisible by 8,
  1364. // but we don't expect to get this case in practice. This is just so that the code works for that case.
  1365. kcache.copy_(kcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
  1366. vcache.copy_(vcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
  1367. }
  1368. }
  1369. if (seqlenq_ngroups_swapped) {
  1370. out = out.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size_og});
  1371. softmax_lse = softmax_lse.reshape({batch_size, num_heads_k * seqlen_q, 1});
  1372. }
  1373. return {out, softmax_lse};
  1374. }
  1375. PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  1376. m.doc() = "FlashAttention";
  1377. m.def("fwd", &mha_fwd, "Forward pass");
  1378. m.def("bwd", &mha_bwd, "Backward pass");
  1379. m.def("varlen_fwd", &mha_varlen_fwd, "Forward pass (variable length)");
  1380. m.def("varlen_bwd", &mha_varlen_bwd, "Varlen backward pass");
  1381. m.def("fwd_kvcache", &mha_fwd_kvcache, "Forward pass, with KV-cache");
  1382. }