flash_api.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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. // HEADDIM_SWITCH(params.d, kHeadSize, [&] {
  388. // run_mha_fwd_<cutlass::float_e4m3_t, kHeadSize>(params, stream);
  389. // });
  390. // run_mha_fwd_<cutlass::float_e4m3_t, 128>(params, stream);
  391. #if 0
  392. if (!params.is_e4m3) {
  393. if (params.is_bf16) {
  394. if (params.d == 64) {
  395. run_mha_fwd_<cutlass::bfloat16_t, 64>(params, stream);
  396. } else if (params.d == 128) {
  397. run_mha_fwd_<cutlass::bfloat16_t, 128>(params, stream);
  398. } else {
  399. run_mha_fwd_<cutlass::bfloat16_t, 256>(params, stream);
  400. }
  401. } else {
  402. if (params.d == 64) {
  403. run_mha_fwd_<cutlass::half_t, 64>(params, stream);
  404. } else if (params.d == 128) {
  405. run_mha_fwd_<cutlass::half_t, 128>(params, stream);
  406. } else {
  407. run_mha_fwd_<cutlass::half_t, 256>(params, stream);
  408. }
  409. }
  410. } else {
  411. if (params.d == 64) {
  412. run_mha_fwd_<cutlass::float_e4m3_t, 64>(params, stream);
  413. } else if (params.d == 128) {
  414. run_mha_fwd_<cutlass::float_e4m3_t, 128>(params, stream);
  415. } else if (params.d == 256) {
  416. run_mha_fwd_<cutlass::float_e4m3_t, 256>(params, stream);
  417. }
  418. }
  419. #endif
  420. }
  421. std::vector<at::Tensor>
  422. mha_fwd(at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  423. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  424. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  425. c10::optional<at::Tensor> &out_, // batch_size x seqlen_q x num_heads x head_size
  426. const float softmax_scale,
  427. c10::optional<at::Tensor> &descale_q_, // 1
  428. c10::optional<at::Tensor> &descale_k_, // 1
  429. c10::optional<at::Tensor> &descale_v_, // 1
  430. bool is_causal,
  431. int window_size_left,
  432. int window_size_right,
  433. bool use_gqa_packing = false
  434. ) {
  435. auto dprops = at::cuda::getCurrentDeviceProperties();
  436. bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
  437. TORCH_CHECK(is_sm90, "FlashAttention-3 only supports Hopper GPUs or newer.");
  438. auto q_dtype = q.dtype();
  439. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
  440. "FlashAttention-3 only support fp16, bf16, or fp8 e4m3 data type");
  441. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  442. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  443. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  444. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  445. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  446. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  447. const auto sizes = q.sizes();
  448. const int batch_size = sizes[0];
  449. int seqlen_q = sizes[1];
  450. int num_heads = sizes[2];
  451. const int head_size_og = sizes[3];
  452. const int seqlen_k = k.size(1);
  453. const int num_heads_k = k.size(2);
  454. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  455. TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
  456. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  457. // Guard against mistaken setting of gqa flag
  458. if (num_heads == num_heads_k) { use_gqa_packing = false; }
  459. TORCH_CHECK(head_size_og == 64 || head_size_og == 128 || head_size_og == 256, "Only support head size 64, 128, and 256 for now");
  460. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
  461. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size_og);
  462. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size_og);
  463. at::Tensor q_padded, k_padded, v_padded;
  464. if (head_size_og % 8 != 0) {
  465. q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  466. k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  467. v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  468. } else {
  469. q_padded = q;
  470. k_padded = k;
  471. v_padded = v;
  472. }
  473. at::Tensor out;
  474. if (out_.has_value()) {
  475. out = out_.value();
  476. // TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  477. TORCH_CHECK(q_dtype == at::ScalarType::Float8_e4m3fn
  478. ? (out.dtype() == at::kBFloat16)
  479. : (out.dtype() == q_dtype),
  480. "Output must have the same dtype as input dtype if dtype is "
  481. "not fp8, or fp16 for fp8 input.");
  482. CHECK_DEVICE(out);
  483. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  484. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og);
  485. if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
  486. } else {
  487. if (q_dtype == at::ScalarType::Float8_e4m3fn)
  488. out = torch::empty_like(q_padded, at::kBFloat16);
  489. else
  490. out = torch::empty_like(q_padded);
  491. }
  492. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  493. const int head_size = round_multiple(head_size_og, 8);
  494. const int head_size_rounded = round_multiple(head_size, 32);
  495. const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
  496. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  497. if (is_causal) { window_size_right = 0; }
  498. // Otherwise the kernel will be launched from cuda:0 device
  499. // Cast to char to avoid compiler warning about narrowing
  500. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  501. auto opts = q.options();
  502. auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  503. at::Tensor p;
  504. Flash_fwd_params params;
  505. set_params_fprop(params,
  506. batch_size, batch_size,
  507. seqlen_q, seqlen_k,
  508. seqlen_q_rounded, seqlen_k_rounded,
  509. num_heads, num_heads_k,
  510. head_size, head_size_rounded,
  511. q_padded, k_padded, v_padded, out,
  512. /*cu_seqlens_q_d=*/nullptr,
  513. /*cu_seqlens_k_d=*/nullptr,
  514. /*seqused_q=*/nullptr,
  515. /*seqused_k=*/nullptr,
  516. nullptr,
  517. softmax_lse.data_ptr(),
  518. /*p_dropout=*/0.f,
  519. softmax_scale,
  520. /*window_size_left=*/window_size_left,
  521. /*window_size_right=*/window_size_right);
  522. auto tile_count_semaphore = is_causal || params.is_local
  523. ? torch::zeros({1}, opts.dtype(torch::kInt32)) : torch::empty({1}, opts.dtype(torch::kInt32));
  524. params.tile_count_semaphore = tile_count_semaphore.data_ptr<int>();
  525. at::Tensor descale_q, descale_k, descale_v;
  526. if(q_dtype == at::ScalarType::Float8_e4m3fn) {
  527. if (descale_q_.has_value()) {
  528. descale_q = descale_q_.value();
  529. CHECK_DEVICE(descale_q);
  530. CHECK_SHAPE(descale_q, 1);
  531. } else { descale_q = torch::ones({1}, opts.dtype(at::kFloat)); }
  532. if (descale_k_.has_value()) {
  533. descale_k = descale_k_.value();
  534. CHECK_DEVICE(descale_k);
  535. CHECK_SHAPE(descale_k, 1);
  536. } else { descale_k = torch::ones({1}, opts.dtype(at::kFloat)); }
  537. if (descale_v_.has_value()) {
  538. descale_v = descale_v_.value();
  539. CHECK_DEVICE(descale_v);
  540. CHECK_SHAPE(descale_v, 1);
  541. } else { descale_v = torch::ones({1}, opts.dtype(at::kFloat)); }
  542. params.descale_q_ptr = descale_q.data_ptr<float>();
  543. params.descale_k_ptr = descale_k.data_ptr<float>();
  544. params.descale_v_ptr = descale_v.data_ptr<float>();
  545. } else {
  546. params.descale_q_ptr = nullptr;
  547. params.descale_k_ptr = nullptr;
  548. params.descale_v_ptr = nullptr;
  549. }
  550. params.use_gqa_packing = use_gqa_packing;
  551. if (seqlen_k > 0) {
  552. auto stream = at::cuda::getCurrentCUDAStream().stream();
  553. run_mha_fwd(params, stream);
  554. } else {
  555. // If seqlen_k == 0, then we have an empty tensor. We need to set the output to 0.
  556. out.zero_();
  557. softmax_lse.fill_(std::numeric_limits<float>::infinity());
  558. }
  559. at::Tensor out_padded = out;
  560. if (head_size_og % 8 != 0) {
  561. out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  562. if (out_.has_value()) { out_.value().copy_(out); }
  563. }
  564. return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p};
  565. }
  566. std::vector<at::Tensor>
  567. mha_varlen_fwd(at::Tensor &q, // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
  568. 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.
  569. 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.
  570. c10::optional<at::Tensor> &out_, // total_q x num_heads x head_size, total_k := \sum_{i=0}^{b} s_i
  571. const at::Tensor &cu_seqlens_q, // b+1
  572. const at::Tensor &cu_seqlens_k, // b+1
  573. c10::optional<at::Tensor> &seqused_q, // b. If given, only this many elements of each batch element's queries and outputs are used.
  574. c10::optional<at::Tensor> &seqused_k, // b. If given, only this many elements of each batch element's keys are used.
  575. int max_seqlen_q,
  576. const int max_seqlen_k,
  577. const float softmax_scale,
  578. c10::optional<at::Tensor> &descale_q_, // 1
  579. c10::optional<at::Tensor> &descale_k_, // 1
  580. c10::optional<at::Tensor> &descale_v_, // 1
  581. bool is_causal,
  582. int window_size_left,
  583. int window_size_right) {
  584. auto dprops = at::cuda::getCurrentDeviceProperties();
  585. bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
  586. TORCH_CHECK(is_sm90, "FlashAttention only supports Hopper GPUs or newer.");
  587. auto q_dtype = q.dtype();
  588. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
  589. "FlashAttention-3 varlen only support fp16, bf16, or fp8 e4m3 data type");
  590. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  591. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  592. TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
  593. TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");
  594. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  595. CHECK_DEVICE(cu_seqlens_q);
  596. CHECK_DEVICE(cu_seqlens_k);
  597. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  598. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  599. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  600. CHECK_CONTIGUOUS(cu_seqlens_q);
  601. CHECK_CONTIGUOUS(cu_seqlens_k);
  602. const auto sizes = q.sizes();
  603. const int batch_size = cu_seqlens_q.numel() - 1;
  604. int num_heads = sizes[1];
  605. const int head_size_og = sizes[2];
  606. const int num_heads_k = k.size(1);
  607. void *cu_seqlens_q_d = cu_seqlens_q.data_ptr();
  608. const int total_q = q.sizes()[0];
  609. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  610. TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
  611. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  612. CHECK_SHAPE(q, total_q, num_heads, head_size_og);
  613. const int total_k = k.size(0);
  614. CHECK_SHAPE(k, total_k, num_heads_k, head_size_og);
  615. CHECK_SHAPE(v, total_k, num_heads_k, head_size_og);
  616. CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
  617. if (seqused_q.has_value()){
  618. auto seqused_q_ = seqused_q.value();
  619. TORCH_CHECK(seqused_q_.dtype() == torch::kInt32, "seqused_q must have dtype int32");
  620. TORCH_CHECK(seqused_q_.is_cuda(), "seqused_q must be on CUDA device");
  621. TORCH_CHECK(seqused_q_.is_contiguous(), "seqused_q must be contiguous");
  622. CHECK_SHAPE(seqused_q_, batch_size);
  623. }
  624. CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
  625. if (seqused_k.has_value()){
  626. auto seqused_k_ = seqused_k.value();
  627. TORCH_CHECK(seqused_k_.dtype() == torch::kInt32, "seqused_k must have dtype int32");
  628. TORCH_CHECK(seqused_k_.is_cuda(), "seqused_k must be on CUDA device");
  629. TORCH_CHECK(seqused_k_.is_contiguous(), "seqused_k must be contiguous");
  630. CHECK_SHAPE(seqused_k_, batch_size);
  631. }
  632. at::Tensor q_padded, k_padded, v_padded;
  633. if (head_size_og % 8 != 0) {
  634. q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  635. k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  636. v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  637. } else {
  638. q_padded = q;
  639. k_padded = k;
  640. v_padded = v;
  641. }
  642. at::Tensor out;
  643. if (out_.has_value()) {
  644. out = out_.value();
  645. TORCH_CHECK(q_dtype == at::ScalarType::Float8_e4m3fn
  646. ? (out.dtype() == at::kBFloat16)
  647. : (out.dtype() == q_dtype),
  648. "Output must have the same dtype as input dtype if dtype is "
  649. "not fp8, or fp16 for fp8 input.");
  650. CHECK_DEVICE(out);
  651. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  652. CHECK_SHAPE(out, sizes[0], sizes[1], head_size_og);
  653. if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
  654. } else {
  655. if (q_dtype == at::ScalarType::Float8_e4m3fn)
  656. out = torch::empty_like(q_padded, at::kBFloat16);
  657. else
  658. out = torch::empty_like(q_padded);
  659. }
  660. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  661. const int head_size = round_multiple(head_size_og, 8);
  662. const int head_size_rounded = round_multiple(head_size, 32);
  663. const int seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
  664. const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
  665. if (is_causal) { window_size_right = 0; }
  666. // Otherwise the kernel will be launched from cuda:0 device
  667. // Cast to char to avoid compiler warning about narrowing
  668. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  669. auto opts = q.options();
  670. auto softmax_lse = torch::empty({num_heads, total_q}, opts.dtype(at::kFloat));
  671. Flash_fwd_params params;
  672. set_params_fprop(params,
  673. batch_size, batch_size,
  674. max_seqlen_q, max_seqlen_k,
  675. seqlen_q_rounded, seqlen_k_rounded,
  676. num_heads, num_heads_k,
  677. head_size, head_size_rounded,
  678. q_padded, k_padded, v_padded, out,
  679. cu_seqlens_q_d,
  680. cu_seqlens_k.data_ptr(),
  681. seqused_q.has_value() ? seqused_q.value().data_ptr() : nullptr,
  682. seqused_k.has_value() ? seqused_k.value().data_ptr() : nullptr,
  683. /*p_d=*/nullptr,
  684. softmax_lse.data_ptr(),
  685. /*p_dropout=*/0.f,
  686. softmax_scale,
  687. window_size_left,
  688. window_size_right,
  689. /*seqlenq_ngroups_swapped=*/false,
  690. /*unpadded_lse=*/true);
  691. params.total_q = total_q;
  692. params.total_k = total_k;
  693. // auto tile_count_semaphore = is_causal || params.is_local
  694. // ? torch::zeros({1}, opts.dtype(torch::kInt32)) : torch::empty({1}, opts.dtype(torch::kInt32));
  695. auto tile_count_semaphore = torch::zeros({1}, opts.dtype(torch::kInt32));
  696. params.tile_count_semaphore = tile_count_semaphore.data_ptr<int>();
  697. at::Tensor descale_q, descale_k, descale_v;
  698. if(q_dtype == at::ScalarType::Float8_e4m3fn) {
  699. if (descale_q_.has_value()) {
  700. descale_q = descale_q_.value();
  701. CHECK_DEVICE(descale_q);
  702. CHECK_SHAPE(descale_q, 1);
  703. } else { descale_q = torch::ones({1}, opts.dtype(at::kFloat)); }
  704. if (descale_k_.has_value()) {
  705. descale_k = descale_k_.value();
  706. CHECK_DEVICE(descale_k);
  707. CHECK_SHAPE(descale_k, 1);
  708. } else { descale_k = torch::ones({1}, opts.dtype(at::kFloat)); }
  709. if (descale_v_.has_value()) {
  710. descale_v = descale_v_.value();
  711. CHECK_DEVICE(descale_v);
  712. CHECK_SHAPE(descale_v, 1);
  713. } else { descale_v = torch::ones({1}, opts.dtype(at::kFloat)); }
  714. params.descale_q_ptr = descale_q.data_ptr<float>();
  715. params.descale_k_ptr = descale_k.data_ptr<float>();
  716. params.descale_v_ptr = descale_v.data_ptr<float>();
  717. } else {
  718. params.descale_q_ptr = nullptr;
  719. params.descale_k_ptr = nullptr;
  720. params.descale_v_ptr = nullptr;
  721. }
  722. if (max_seqlen_k > 0) {
  723. auto stream = at::cuda::getCurrentCUDAStream().stream();
  724. run_mha_fwd(params, stream);
  725. } else {
  726. // If seqlen_k == 0, then we have an empty tensor. We need to set the output to 0.
  727. out.zero_();
  728. softmax_lse.fill_(std::numeric_limits<float>::infinity());
  729. }
  730. at::Tensor out_padded = out;
  731. if (head_size_og % 8 != 0) {
  732. out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  733. if (out_.has_value()) { out_.value().copy_(out); }
  734. }
  735. return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse};
  736. }
  737. void run_mha_bwd(Flash_bwd_params &params, cudaStream_t stream) {
  738. // FP16_SWITCH(!params.is_bf16, [&] {
  739. // HEADDIM_SWITCH(params.d, [&] {
  740. // run_mha_bwd_<elem_type, kHeadDim>(params, stream);
  741. // });
  742. // });
  743. // if (!params.is_bf16) {
  744. // if (params.d <= 64) {
  745. // run_mha_bwd_<cutlass::half_t, 64>(params, stream);
  746. // } else if (params.d <= 96) {
  747. // run_mha_bwd_<cutlass::half_t, 96>(params, stream);
  748. // } else {
  749. // run_mha_bwd_<cutlass::half_t, 128>(params, stream);
  750. // }
  751. // } else {
  752. // if (params.d <= 64) {
  753. // run_mha_bwd_<cutlass::bfloat16_t, 64>(params, stream);
  754. // } else if (params.d <= 96) {
  755. // run_mha_bwd_<cutlass::bfloat16_t, 96>(params, stream);
  756. // } else {
  757. // run_mha_bwd_<cutlass::bfloat16_t, 128>(params, stream);
  758. // }
  759. // }
  760. }
  761. std::vector<at::Tensor>
  762. mha_bwd(const at::Tensor &dout, // batch_size x seqlen_q x num_heads, x head_size_og
  763. const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  764. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  765. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  766. const at::Tensor &out, // batch_size x seqlen_q x num_heads x head_size
  767. const at::Tensor &softmax_lse, // b x h x seqlen_q
  768. c10::optional<at::Tensor> &dq_, // batch_size x seqlen_q x num_heads x head_size
  769. c10::optional<at::Tensor> &dk_, // batch_size x seqlen_k x num_heads_k x head_size
  770. c10::optional<at::Tensor> &dv_, // batch_size x seqlen_k x num_heads_k x head_size
  771. const float softmax_scale,
  772. const bool is_causal,
  773. int window_size_left,
  774. int window_size_right,
  775. const bool deterministic) {
  776. #ifdef FLASHATTENTION_DISABLE_BACKWARD
  777. TORCH_CHECK(false, "This flash attention build does not support backward.");
  778. #endif
  779. auto dprops = at::cuda::getCurrentDeviceProperties();
  780. bool is_sm9x = dprops->major == 9 && dprops->minor >= 0;
  781. TORCH_CHECK(is_sm9x, "FlashAttentionHopper only supports Hopper GPUs or newer.");
  782. auto stream = at::cuda::getCurrentCUDAStream().stream();
  783. auto q_dtype = q.dtype();
  784. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  785. "FlashAttention only support fp16 and bf16 data type");
  786. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  787. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  788. TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
  789. TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
  790. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  791. CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
  792. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  793. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  794. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  795. TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
  796. TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
  797. const auto sizes = q.sizes();
  798. const int batch_size = sizes[0];
  799. const int seqlen_q = sizes[1];
  800. const int num_heads = sizes[2];
  801. const int head_size_og = dout.size(3);
  802. const int head_size = sizes[3];
  803. const int seqlen_k = k.size(1);
  804. const int num_heads_k = k.size(2);
  805. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  806. TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
  807. TORCH_CHECK(head_size <= 128, "FlashAttention backward only supports head dimension at most 128");
  808. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  809. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  810. const int head_size_rounded = head_size <= 64 ? 64 : round_multiple(head_size, 32);
  811. // This should match the kernel configs
  812. const int kBlockM = head_size <= 64 ? 128 : (head_size < 256 ? 64 : 32);
  813. const int seqlen_q_rounded = round_multiple(seqlen_q, kBlockM);
  814. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  815. TORCH_CHECK(head_size == round_multiple(head_size_og, 8), "head_size must be head_size_og rounded to a multiple of 8");
  816. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size);
  817. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size);
  818. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size);
  819. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size);
  820. CHECK_SHAPE(dout, batch_size, seqlen_q, num_heads, head_size_og);
  821. at::Tensor dq, dk, dv;
  822. if (dq_.has_value()) {
  823. dq = dq_.value();
  824. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  825. CHECK_DEVICE(dq);
  826. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  827. CHECK_SHAPE(dq, batch_size, seqlen_q, num_heads, head_size);
  828. } else {
  829. dq = torch::empty_like(q);
  830. }
  831. if (dk_.has_value()) {
  832. dk = dk_.value();
  833. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  834. CHECK_DEVICE(dk);
  835. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  836. CHECK_SHAPE(dk, batch_size, seqlen_k, num_heads_k, head_size);
  837. } else {
  838. dk = torch::empty_like(k);
  839. }
  840. if (dv_.has_value()) {
  841. dv = dv_.value();
  842. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  843. CHECK_DEVICE(dv);
  844. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  845. CHECK_SHAPE(dv, batch_size, seqlen_k, num_heads_k, head_size);
  846. } else {
  847. dv = torch::empty_like(v);
  848. }
  849. at::Tensor dout_padded;
  850. if (head_size_og % 8 != 0) {
  851. dout_padded = torch::nn::functional::pad(dout, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  852. } else {
  853. dout_padded = dout;
  854. }
  855. // Otherwise the kernel will be launched from cuda:0 device
  856. // Cast to char to avoid compiler warning about narrowing
  857. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  858. auto opts = q.options();
  859. // Need softmax_d to have seqlen_q_rounded since we want its address to be aligned by 16/8 bytes for TMA / LDG.64
  860. auto softmax_d = torch::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
  861. auto softmax_lse_log2 = torch::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
  862. at::Tensor dq_accum;
  863. at::Tensor dk_accum, dv_accum;
  864. dq_accum = torch::empty({batch_size, num_heads, seqlen_q_rounded, head_size_rounded}, opts.dtype(at::kFloat));
  865. // dk_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  866. // dv_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  867. at::Tensor dk_expanded, dv_expanded;
  868. if (num_heads_k != num_heads) { // MQA / GQA
  869. dk_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  870. dv_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  871. } else {
  872. dk_expanded = dk;
  873. dv_expanded = dv;
  874. }
  875. if (is_causal) { window_size_right = 0; }
  876. Flash_bwd_params params;
  877. set_params_dgrad(params,
  878. batch_size,
  879. seqlen_q, seqlen_k,
  880. seqlen_q_rounded, seqlen_k_rounded,
  881. num_heads, num_heads_k,
  882. head_size, head_size_rounded,
  883. q, k, v, out,
  884. dout_padded, dq, dk_expanded, dv_expanded,
  885. /*cu_seqlens_q_d=*/nullptr,
  886. /*cu_seqlens_k_d=*/nullptr,
  887. /*seqused_q=*/nullptr,
  888. /*seqused_k=*/nullptr,
  889. dq_accum.data_ptr(),
  890. // loop ? dk_accum.data_ptr() : nullptr,
  891. // loop ? dv_accum.data_ptr() : nullptr,
  892. nullptr,
  893. nullptr,
  894. softmax_lse.data_ptr(),
  895. softmax_d.data_ptr(),
  896. /*p_dropout=*/0.f,
  897. softmax_scale,
  898. /*window_size_left=*/window_size_left,
  899. /*window_size_right=*/window_size_right,
  900. deterministic);
  901. params.softmax_lse_log2_ptr = softmax_lse_log2.data_ptr();
  902. // Will be zero'ed out in the backward preprocess kernel
  903. at::Tensor dq_semaphore = torch::empty({(seqlen_q + kBlockM - 1) / kBlockM, batch_size, num_heads}, opts.dtype(torch::kInt32));
  904. params.dq_semaphore = dq_semaphore.data_ptr<int>();
  905. // printf("dq_semaphore: %p, [%d, %d, %d]\n", params.dq_semaphore, (seqlen_q + 64 - 1) / 64, batch_size, num_heads);
  906. if (seqlen_q > 0) {
  907. run_mha_bwd(params, stream);
  908. } else {
  909. // If seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  910. dk_expanded.zero_();
  911. dv_expanded.zero_();
  912. softmax_d.zero_();
  913. }
  914. // For MQA/GQA we need to sum dK and dV across the groups
  915. if (num_heads_k != num_heads) {
  916. at::sum_out(dk, at::reshape(dk_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  917. at::sum_out(dv, at::reshape(dv_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  918. }
  919. if (head_size_og % 8 != 0) {
  920. dq = dq.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  921. dk = dk.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  922. dv = dv.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  923. }
  924. return { dq, dk, dv, softmax_d, dq_accum};
  925. }
  926. std::vector<at::Tensor>
  927. mha_varlen_bwd(const at::Tensor &dout, // batch_size x seqlen_q x num_heads, x head_size_og
  928. const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  929. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  930. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  931. const at::Tensor &out, // batch_size x seqlen_q x num_heads x head_size
  932. const at::Tensor &softmax_lse, // b x h x seqlen_q
  933. c10::optional<at::Tensor> &dq_, // batch_size x seqlen_q x num_heads x head_size
  934. c10::optional<at::Tensor> &dk_, // batch_size x seqlen_k x num_heads_k x head_size
  935. c10::optional<at::Tensor> &dv_, // batch_size x seqlen_k x num_heads_k x head_size
  936. const at::Tensor &cu_seqlens_q, // b+1
  937. const at::Tensor &cu_seqlens_k, // b+1
  938. c10::optional<at::Tensor> &seqused_q, // b. If given, only this many elements of each batch element's queries and outputs are used.
  939. c10::optional<at::Tensor> &seqused_k, // b. If given, only this many elements of each batch element's keys are used.
  940. const int max_seqlen_q,
  941. const int max_seqlen_k, // max sequence length to choose the kernel
  942. const float softmax_scale,
  943. const bool is_causal,
  944. int window_size_left,
  945. int window_size_right,
  946. const bool deterministic) {
  947. #ifdef FLASHATTENTION_DISABLE_BACKWARD
  948. TORCH_CHECK(false, "This flash attention build does not support backward.");
  949. #endif
  950. auto dprops = at::cuda::getCurrentDeviceProperties();
  951. bool is_sm9x = dprops->major == 9 && dprops->minor >= 0;
  952. TORCH_CHECK(is_sm9x, "FlashAttentionHopper only supports Hopper GPUs or newer.");
  953. auto stream = at::cuda::getCurrentCUDAStream().stream();
  954. auto q_dtype = q.dtype();
  955. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  956. "FlashAttention only support fp16 and bf16 data type");
  957. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  958. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  959. TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
  960. TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
  961. TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
  962. TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");
  963. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  964. CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
  965. CHECK_DEVICE(cu_seqlens_q); CHECK_DEVICE(cu_seqlens_k);
  966. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  967. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  968. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  969. TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
  970. TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
  971. CHECK_CONTIGUOUS(cu_seqlens_q);
  972. CHECK_CONTIGUOUS(cu_seqlens_k);
  973. const auto sizes = q.sizes();
  974. const int total_q = sizes[0];
  975. const int batch_size = cu_seqlens_q.numel() - 1;
  976. const int num_heads = sizes[1];
  977. const int head_size_og = dout.size(2);
  978. const int head_size = sizes[2];
  979. const int total_k = k.size(0);
  980. const int num_heads_k = k.size(1);
  981. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  982. TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
  983. TORCH_CHECK(head_size <= 128, "FlashAttention backward only supports head dimension at most 128");
  984. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  985. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  986. const int head_size_rounded = head_size <= 64 ? 64 : round_multiple(head_size, 32);
  987. // This should match the kernel configs
  988. const int kBlockM = head_size <= 64 ? 128 : (head_size < 256 ? 64 : 32);
  989. const int seqlen_q_rounded = round_multiple(max_seqlen_q, kBlockM);
  990. const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
  991. int const total_q_padded_rounded = round_multiple(total_q + batch_size * 128, 128);
  992. TORCH_CHECK(head_size == round_multiple(head_size_og, 8), "head_size must be head_size_og rounded to a multiple of 8");
  993. CHECK_SHAPE(q, total_q, num_heads, head_size_og);
  994. CHECK_SHAPE(k, total_k, num_heads_k, head_size_og);
  995. CHECK_SHAPE(v, total_k, num_heads_k, head_size_og);
  996. CHECK_SHAPE(out, total_q, num_heads, head_size);
  997. CHECK_SHAPE(dout, total_q, num_heads, head_size_og);
  998. CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
  999. if (seqused_q.has_value()){
  1000. auto seqused_q_ = seqused_q.value();
  1001. TORCH_CHECK(seqused_q_.dtype() == torch::kInt32, "seqused_q must have dtype int32");
  1002. TORCH_CHECK(seqused_q_.is_cuda(), "seqused_q must be on CUDA device");
  1003. TORCH_CHECK(seqused_q_.is_contiguous(), "seqused_q must be contiguous");
  1004. CHECK_SHAPE(seqused_q_, batch_size);
  1005. }
  1006. CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
  1007. if (seqused_k.has_value()){
  1008. auto seqused_k_ = seqused_k.value();
  1009. TORCH_CHECK(seqused_k_.dtype() == torch::kInt32, "seqused_k must have dtype int32");
  1010. TORCH_CHECK(seqused_k_.is_cuda(), "seqused_k must be on CUDA device");
  1011. TORCH_CHECK(seqused_k_.is_contiguous(), "seqused_k must be contiguous");
  1012. CHECK_SHAPE(seqused_k_, batch_size);
  1013. }
  1014. at::Tensor dq, dk, dv;
  1015. if (dq_.has_value()) {
  1016. dq = dq_.value();
  1017. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  1018. CHECK_DEVICE(dq);
  1019. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  1020. CHECK_SHAPE(dq, total_q, num_heads, head_size);
  1021. } else {
  1022. dq = torch::empty_like(q);
  1023. }
  1024. if (dk_.has_value()) {
  1025. dk = dk_.value();
  1026. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  1027. CHECK_DEVICE(dk);
  1028. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  1029. CHECK_SHAPE(dk, total_k, num_heads_k, head_size);
  1030. } else {
  1031. dk = torch::empty_like(k);
  1032. }
  1033. if (dv_.has_value()) {
  1034. dv = dv_.value();
  1035. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  1036. CHECK_DEVICE(dv);
  1037. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  1038. CHECK_SHAPE(dv, total_k, num_heads_k, head_size);
  1039. } else {
  1040. dv = torch::empty_like(v);
  1041. }
  1042. at::Tensor dout_padded;
  1043. if (head_size_og % 8 != 0) {
  1044. dout_padded = torch::nn::functional::pad(dout, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1045. } else {
  1046. dout_padded = dout;
  1047. }
  1048. if (is_causal) { window_size_right = 0; }
  1049. // Otherwise the kernel will be launched from cuda:0 device
  1050. // Cast to char to avoid compiler warning about narrowing
  1051. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  1052. auto opts = q.options();
  1053. // 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
  1054. auto softmax_d = torch::empty({num_heads, total_q_padded_rounded}, opts.dtype(at::kFloat));
  1055. auto softmax_lse_log2 = torch::empty({num_heads, total_q_padded_rounded}, opts.dtype(at::kFloat));
  1056. at::Tensor dq_accum;
  1057. at::Tensor dk_accum, dv_accum;
  1058. dq_accum = torch::empty({num_heads, total_q_padded_rounded, head_size_rounded}, opts.dtype(at::kFloat));
  1059. // dk_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  1060. // dv_accum = torch::zeros({batch_size, seqlen_k_rounded, num_heads_k, head_size_rounded}, opts.dtype(at::kFloat));
  1061. at::Tensor dk_expanded, dv_expanded;
  1062. if (num_heads_k != num_heads) { // MQA / GQA
  1063. dk_expanded = torch::empty({total_k, num_heads, head_size}, opts);
  1064. dv_expanded = torch::empty({total_k, num_heads, head_size}, opts);
  1065. } else {
  1066. dk_expanded = dk;
  1067. dv_expanded = dv;
  1068. }
  1069. Flash_bwd_params params;
  1070. set_params_dgrad(params,
  1071. batch_size,
  1072. max_seqlen_q, max_seqlen_k,
  1073. seqlen_q_rounded, seqlen_k_rounded,
  1074. num_heads, num_heads_k,
  1075. head_size, head_size_rounded,
  1076. q, k, v, out,
  1077. dout_padded, dq, dk_expanded, dv_expanded,
  1078. cu_seqlens_q.data_ptr(),
  1079. cu_seqlens_k.data_ptr(),
  1080. seqused_q.has_value() ? seqused_q.value().data_ptr() : nullptr,
  1081. seqused_k.has_value() ? seqused_k.value().data_ptr() : nullptr,
  1082. dq_accum.data_ptr(),
  1083. // loop ? dk_accum.data_ptr() : nullptr,
  1084. // loop ? dv_accum.data_ptr() : nullptr,
  1085. nullptr,
  1086. nullptr,
  1087. softmax_lse.data_ptr(),
  1088. softmax_d.data_ptr(),
  1089. /*p_dropout=*/0.f,
  1090. softmax_scale,
  1091. /*window_size_left=*/window_size_left,
  1092. /*window_size_right=*/window_size_right,
  1093. deterministic);
  1094. params.total_q = total_q;
  1095. params.total_k = total_k;
  1096. params.softmax_lse_log2_ptr = softmax_lse_log2.data_ptr();
  1097. // Will be zero'ed out in the backward preprocess kernel
  1098. at::Tensor dq_semaphore = torch::empty({(max_seqlen_q + kBlockM - 1) / kBlockM, batch_size, num_heads}, opts.dtype(torch::kInt32));
  1099. params.dq_semaphore = dq_semaphore.data_ptr<int>();
  1100. if (max_seqlen_q > 0) {
  1101. run_mha_bwd(params, stream);
  1102. } else {
  1103. // If max_seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  1104. dk_expanded.zero_();
  1105. dv_expanded.zero_();
  1106. softmax_d.zero_();
  1107. }
  1108. // For MQA/GQA we need to sum dK and dV across the groups
  1109. if (num_heads_k != num_heads) {
  1110. at::sum_out(dk, at::reshape(dk_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
  1111. at::sum_out(dv, at::reshape(dv_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
  1112. }
  1113. if (head_size_og % 8 != 0) {
  1114. dq = dq.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1115. dk = dk.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1116. dv = dv.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1117. }
  1118. return { dq, dk, dv, softmax_d, dq_accum, softmax_lse_log2 };
  1119. }
  1120. std::vector<at::Tensor>
  1121. mha_fwd_kvcache(at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  1122. 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.
  1123. 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.
  1124. c10::optional<const at::Tensor> &k_, // batch_size x seqlen_knew x num_heads_k x head_size
  1125. c10::optional<const at::Tensor> &v_, // batch_size x seqlen_knew x num_heads_k x head_size
  1126. c10::optional<const at::Tensor> &seqlens_k_, // batch_size
  1127. c10::optional<const at::Tensor> &rotary_cos_, // seqlen_ro x (rotary_dim / 2)
  1128. c10::optional<const at::Tensor> &rotary_sin_, // seqlen_ro x (rotary_dim / 2)
  1129. c10::optional<const at::Tensor> &cache_batch_idx_, // indices to index into the KV cache
  1130. c10::optional<const at::Tensor> &leftpad_k_, // batch_size
  1131. c10::optional<at::Tensor> &block_table_, // batch_size x max_num_blocks_per_seq
  1132. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
  1133. c10::optional<at::Tensor> &out_, // batch_size x seqlen_q x num_heads x head_size
  1134. const float softmax_scale,
  1135. c10::optional<at::Tensor> &descale_q_, // 1
  1136. c10::optional<at::Tensor> &descale_k_, // 1
  1137. c10::optional<at::Tensor> &descale_v_, // 1
  1138. bool is_causal,
  1139. int window_size_left,
  1140. int window_size_right,
  1141. const float softcap,
  1142. bool is_rotary_interleaved, // if true, rotary combines indices 0 & 1, else indices 0 & rotary_dim / 2
  1143. int num_splits,
  1144. int max_seqlen_k_hint,
  1145. bool use_gqa_packing
  1146. ) {
  1147. auto dprops = at::cuda::getCurrentDeviceProperties();
  1148. // bool is_sm75 = dprops->major == 7 && dprops->minor == 5;
  1149. // bool is_sm8x = dprops->major == 8 && dprops->minor >= 0;
  1150. bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
  1151. TORCH_CHECK(is_sm90, "FlashAttention-3 only supports Hopper GPUs or newer.");
  1152. auto q_dtype = q.dtype();
  1153. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
  1154. "FlashAttention-3 only support fp16, bf16, or fp8 e4m3 data type");
  1155. TORCH_CHECK(kcache.dtype() == q_dtype, "query and key must have the same dtype");
  1156. TORCH_CHECK(vcache.dtype() == q_dtype, "query and value must have the same dtype");
  1157. CHECK_DEVICE(q); CHECK_DEVICE(kcache); CHECK_DEVICE(vcache);
  1158. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1159. TORCH_CHECK(kcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1160. TORCH_CHECK(vcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  1161. at::Tensor block_table;
  1162. const bool paged_KV = block_table_.has_value();
  1163. if (paged_KV) {
  1164. TORCH_CHECK(!cache_batch_idx_.has_value(), "Paged KVcache does not support cache_batch_idx");
  1165. block_table = block_table_.value();
  1166. CHECK_DEVICE(block_table);
  1167. TORCH_CHECK(block_table.dtype() == torch::kInt32, "block_table must have dtype torch.int32");
  1168. TORCH_CHECK(block_table.stride(-1) == 1, "block_table must have contiguous last dimension");
  1169. }
  1170. const auto sizes = q.sizes();
  1171. const int batch_size = sizes[0];
  1172. int seqlen_q = sizes[1];
  1173. int num_heads = sizes[2];
  1174. const int head_size_og = sizes[3];
  1175. const int max_num_blocks_per_seq = !paged_KV ? 0 : block_table.size(1);
  1176. const int num_blocks = !paged_KV ? 0 : kcache.size(0);
  1177. const int page_block_size = !paged_KV ? 1 : kcache.size(1);
  1178. TORCH_CHECK(!paged_KV || page_block_size % 256 == 0, "Paged KV cache block size must be divisible by 256");
  1179. const int seqlen_k = !paged_KV ? kcache.size(1) : max_num_blocks_per_seq * page_block_size;
  1180. const int num_heads_k = kcache.size(2);
  1181. const int batch_size_c = !paged_KV ? kcache.size(0) : batch_size;
  1182. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  1183. TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
  1184. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  1185. // Guard against mistaken setting of gqa flag
  1186. if (num_heads == num_heads_k) { use_gqa_packing = false; }
  1187. // causal=true is the same as causal=false in this case
  1188. if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }
  1189. if (is_causal) { window_size_right = 0; }
  1190. // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
  1191. // H/t Daniel Haziza
  1192. const int seqlenq_ngroups_swapped =
  1193. seqlen_q == 1 && num_heads > num_heads_k && window_size_left < 0 &&
  1194. window_size_right < 0 && head_size_og % 8 == 0 &&
  1195. !alibi_slopes_.has_value() && !use_gqa_packing;
  1196. if (seqlenq_ngroups_swapped) {
  1197. const int ngroups = num_heads / num_heads_k;
  1198. q = q.reshape({batch_size, num_heads_k, ngroups, head_size_og}).transpose(1, 2);
  1199. seqlen_q = ngroups;
  1200. num_heads = num_heads_k;
  1201. }
  1202. if (window_size_left >= seqlen_k) { window_size_left = -1; }
  1203. if (window_size_right >= seqlen_k) { window_size_right = -1; }
  1204. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
  1205. if (!paged_KV) {
  1206. CHECK_SHAPE(kcache, batch_size_c, seqlen_k, num_heads_k, head_size_og);
  1207. CHECK_SHAPE(vcache, batch_size_c, seqlen_k, num_heads_k, head_size_og);
  1208. } else {
  1209. CHECK_SHAPE(kcache, num_blocks, page_block_size, num_heads_k, head_size_og);
  1210. CHECK_SHAPE(vcache, num_blocks, page_block_size, num_heads_k, head_size_og);
  1211. CHECK_SHAPE(block_table, batch_size, max_num_blocks_per_seq);
  1212. }
  1213. at::Tensor q_padded, kcache_padded, vcache_padded;
  1214. if (head_size_og % 8 != 0) {
  1215. q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1216. kcache_padded = torch::nn::functional::pad(kcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1217. vcache_padded = torch::nn::functional::pad(vcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1218. } else {
  1219. q_padded = q;
  1220. kcache_padded = kcache;
  1221. vcache_padded = vcache;
  1222. }
  1223. at::Tensor out;
  1224. if (out_.has_value()) {
  1225. out = out_.value();
  1226. // TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
  1227. TORCH_CHECK(q_dtype == at::ScalarType::Float8_e4m3fn
  1228. ? (out.dtype() == at::kBFloat16)
  1229. : (out.dtype() == q_dtype),
  1230. "Output must have the same dtype as input dtype if dtype is "
  1231. "not fp8, or fp16 for fp8 input.");
  1232. CHECK_DEVICE(out);
  1233. TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
  1234. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og);
  1235. if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
  1236. } else {
  1237. if (q_dtype == at::ScalarType::Float8_e4m3fn) {
  1238. out = torch::empty_like(q_padded, at::kBFloat16);
  1239. }
  1240. else
  1241. out = torch::empty_like(q_padded);
  1242. }
  1243. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  1244. const int head_size = round_multiple(head_size_og, 8);
  1245. const int head_size_rounded = head_size <= 192 ? round_multiple(head_size, 32) : 256;
  1246. const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
  1247. const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
  1248. // Otherwise the kernel will be launched from cuda:0 device
  1249. // Cast to char to avoid compiler warning about narrowing
  1250. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  1251. auto opts = q.options();
  1252. auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  1253. Flash_fwd_params params;
  1254. set_params_fprop(params,
  1255. batch_size, batch_size_c,
  1256. seqlen_q, seqlen_k,
  1257. seqlen_q_rounded, seqlen_k_rounded,
  1258. num_heads, num_heads_k,
  1259. head_size, head_size_rounded,
  1260. q_padded, kcache_padded, vcache_padded, out,
  1261. /*cu_seqlens_q_d=*/nullptr,
  1262. /*cu_seqlens_k_d=*/nullptr,
  1263. /*seqused_q=*/nullptr,
  1264. /*seqused_k=*/nullptr,
  1265. /*p_ptr=*/nullptr,
  1266. softmax_lse.data_ptr(),
  1267. /*p_dropout=*/0.f,
  1268. softmax_scale,
  1269. window_size_left,
  1270. window_size_right
  1271. );
  1272. at::Tensor descale_q, descale_k, descale_v;
  1273. if(q_dtype == at::ScalarType::Float8_e4m3fn) {
  1274. if (descale_q_.has_value()) {
  1275. descale_q = descale_q_.value();
  1276. CHECK_DEVICE(descale_q);
  1277. CHECK_SHAPE(descale_q, 1);
  1278. } else { descale_q = torch::ones({1}, opts.dtype(at::kFloat)); }
  1279. if (descale_k_.has_value()) {
  1280. descale_k = descale_k_.value();
  1281. CHECK_DEVICE(descale_k);
  1282. CHECK_SHAPE(descale_k, 1);
  1283. } else { descale_k = torch::ones({1}, opts.dtype(at::kFloat)); }
  1284. if (descale_v_.has_value()) {
  1285. descale_v = descale_v_.value();
  1286. CHECK_DEVICE(descale_v);
  1287. CHECK_SHAPE(descale_v, 1);
  1288. } else { descale_v = torch::ones({1}, opts.dtype(at::kFloat)); }
  1289. params.descale_q_ptr = descale_q.data_ptr<float>();
  1290. params.descale_k_ptr = descale_k.data_ptr<float>();
  1291. params.descale_v_ptr = descale_v.data_ptr<float>();
  1292. } else {
  1293. params.descale_q_ptr = nullptr;
  1294. params.descale_k_ptr = nullptr;
  1295. params.descale_v_ptr = nullptr;
  1296. }
  1297. params.is_kv_cache = true;
  1298. params.use_gqa_packing = use_gqa_packing;
  1299. at::Tensor k, v, k_padded, v_padded;
  1300. if (k_.has_value()) {
  1301. TORCH_CHECK(v_.has_value(), "If key is supplied, value must also be passed in");
  1302. TORCH_CHECK(seqlens_k_.has_value(), "If key is supplied, seqlens_k must also be passed in");
  1303. TORCH_CHECK(seqlen_q <= seqlen_k, "If key is supplied, it must have seqlen <= the seqlen of the KV cache");
  1304. k = k_.value();
  1305. v = v_.value();
  1306. TORCH_CHECK(k.dtype() == q_dtype, "Key must have the same dtype as query");
  1307. TORCH_CHECK(v.dtype() == q_dtype, "Value must have the same dtype as query");
  1308. CHECK_DEVICE(k); CHECK_DEVICE(v);
  1309. TORCH_CHECK(k.stride(-1) == 1, "Key tensor must have contiguous last dimension");
  1310. TORCH_CHECK(v.stride(-1) == 1, "Value tensor must have contiguous last dimension");
  1311. int seqlen_knew = k.size(1);
  1312. CHECK_SHAPE(k, batch_size, seqlen_knew, num_heads_k, head_size_og);
  1313. CHECK_SHAPE(v, batch_size, seqlen_knew, num_heads_k, head_size_og);
  1314. if (head_size_og % 8 != 0) {
  1315. k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1316. v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  1317. } else {
  1318. k_padded = k;
  1319. v_padded = v;
  1320. }
  1321. params.seqlen_knew = seqlen_knew;
  1322. params.knew_ptr = k_padded.data_ptr();
  1323. params.vnew_ptr = v_padded.data_ptr();
  1324. // All stride are in elements, not bytes.
  1325. params.knew_batch_stride = k_padded.stride(0);
  1326. params.vnew_batch_stride = v_padded.stride(0);
  1327. params.knew_row_stride = k_padded.stride(-3);
  1328. params.vnew_row_stride = v_padded.stride(-3);
  1329. params.knew_head_stride = k_padded.stride(-2);
  1330. params.vnew_head_stride = v_padded.stride(-2);
  1331. }
  1332. if (seqlens_k_.has_value()) {
  1333. auto seqlens_k = seqlens_k_.value();
  1334. TORCH_CHECK(seqlens_k.dtype() == torch::kInt32, "seqlens_k must have dtype int32");
  1335. CHECK_DEVICE(seqlens_k);
  1336. CHECK_CONTIGUOUS(seqlens_k);
  1337. CHECK_SHAPE(seqlens_k, batch_size);
  1338. params.seqused_k = static_cast<int *>(seqlens_k.data_ptr());
  1339. }
  1340. if (leftpad_k_.has_value()) {
  1341. TORCH_CHECK(!paged_KV, "We don't support Paged KV and leftpad_k running at the same time yet");
  1342. auto leftpad_k = leftpad_k_.value();
  1343. TORCH_CHECK(leftpad_k.dtype() == torch::kInt32, "leftpad_k must have dtype int32");
  1344. CHECK_DEVICE(leftpad_k);
  1345. CHECK_CONTIGUOUS(leftpad_k);
  1346. CHECK_SHAPE(leftpad_k, batch_size);
  1347. TORCH_CHECK(false, "Left Padding K is not supported");
  1348. //params.leftpad_k = static_cast<int *>(leftpad_k.data_ptr());
  1349. }
  1350. if (rotary_cos_.has_value()) {
  1351. TORCH_CHECK(k_.has_value(), "If rotary cos/sin are provided, new key / value to be appended to KV cache must also be provided");
  1352. auto rotary_cos = rotary_cos_.value();
  1353. CHECK_DEVICE(rotary_cos);
  1354. params.rotary_dim = rotary_cos.size(1) * 2;
  1355. TORCH_CHECK(params.rotary_dim <= head_size, "rotary_dim must be <= headdim");
  1356. TORCH_CHECK(params.rotary_dim % 16 == 0, "Only rotary dimensions divisible by 16 are currently supported");
  1357. const int seqlen_ro = rotary_cos.size(0);
  1358. TORCH_CHECK(seqlen_ro >= seqlen_k, "cos/sin seqlen must be at least the seqlen of KV cache");
  1359. CHECK_SHAPE(rotary_cos, seqlen_ro, params.rotary_dim / 2);
  1360. CHECK_CONTIGUOUS(rotary_cos);
  1361. TORCH_CHECK(rotary_cos.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");
  1362. TORCH_CHECK(rotary_sin_.has_value(), "If rotary cos is provided, rotary sin must also be provided");
  1363. auto rotary_sin = rotary_sin_.value();
  1364. CHECK_DEVICE(rotary_sin);
  1365. CHECK_SHAPE(rotary_sin, seqlen_ro, params.rotary_dim / 2);
  1366. CHECK_CONTIGUOUS(rotary_sin);
  1367. TORCH_CHECK(rotary_sin.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");
  1368. params.rotary_cos_ptr = rotary_cos.data_ptr();
  1369. params.rotary_sin_ptr = rotary_sin.data_ptr();
  1370. params.is_rotary_interleaved = is_rotary_interleaved;
  1371. } else {
  1372. params.rotary_dim = 0;
  1373. }
  1374. if (cache_batch_idx_.has_value()) {
  1375. auto cache_batch_idx = cache_batch_idx_.value();
  1376. CHECK_DEVICE(cache_batch_idx);
  1377. CHECK_CONTIGUOUS(cache_batch_idx);
  1378. TORCH_CHECK(cache_batch_idx.scalar_type() == torch::kInt32, "cache_batch_idx must have dtype int32");
  1379. params.cache_batch_idx = reinterpret_cast<int *>(cache_batch_idx.data_ptr());
  1380. }
  1381. // Keep references to these tensors to extend their lifetime
  1382. at::Tensor softmax_lse_accum, out_accum;
  1383. std::tie(softmax_lse_accum, out_accum) = set_params_splitkv(
  1384. params, batch_size, num_heads, num_heads_k, head_size, max_seqlen_k_hint, seqlen_q,
  1385. head_size_rounded, /*dropout*/ 0.f, num_splits, dprops, use_gqa_packing, is_causal, opts);
  1386. auto tile_count_semaphore = is_causal || params.is_local || params.num_splits != 1
  1387. ? torch::zeros({1}, opts.dtype(torch::kInt32))
  1388. : torch::empty({1}, opts.dtype(torch::kInt32));
  1389. params.tile_count_semaphore = tile_count_semaphore.data_ptr<int>();
  1390. if (paged_KV) {
  1391. params.block_table = block_table.data_ptr<int>();
  1392. params.block_table_batch_stride = block_table.stride(0);
  1393. }
  1394. params.page_block_size = page_block_size;
  1395. TORCH_CHECK(!alibi_slopes_.has_value(), "Alibi Slopes are not supported yet");
  1396. //set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
  1397. auto stream = at::cuda::getCurrentCUDAStream().stream();
  1398. // Only split kernel supports appending to KV cache, or indexing to the cache with cache_batch_idx,
  1399. // or paged KV cache
  1400. //run_mha_fwd(params, stream, /*force_split_kernel=*/k_.has_value() || cache_batch_idx_.has_value() || paged_KV);
  1401. run_mha_fwd(params, stream);
  1402. if (head_size_og % 8 != 0) {
  1403. out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  1404. if (out_.has_value()) { out_.value().copy_(out); }
  1405. if (k_.has_value()) {
  1406. // It's expensive to copy the KV cache here for the case where head size not divisible by 8,
  1407. // but we don't expect to get this case in practice. This is just so that the code works for that case.
  1408. kcache.copy_(kcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
  1409. vcache.copy_(vcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
  1410. }
  1411. }
  1412. if (seqlenq_ngroups_swapped) {
  1413. out = out.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size_og});
  1414. softmax_lse = softmax_lse.reshape({batch_size, num_heads_k * seqlen_q, 1});
  1415. }
  1416. return {out, softmax_lse};
  1417. }
  1418. PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  1419. m.doc() = "FlashAttention";
  1420. m.def("fwd", &mha_fwd, "Forward pass");
  1421. m.def("bwd", &mha_bwd, "Backward pass");
  1422. m.def("varlen_fwd", &mha_varlen_fwd, "Forward pass (variable length)");
  1423. m.def("varlen_bwd", &mha_varlen_bwd, "Varlen backward pass");
  1424. m.def("fwd_kvcache", &mha_fwd_kvcache, "Forward pass, with KV-cache");
  1425. }