mha_bwd.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /******************************************************************************
  2. * Copyright (c) 2024, Tri Dao.
  3. ******************************************************************************/
  4. #include "flash_common.hpp"
  5. #include "fmha_bwd.hpp"
  6. #include "mask.hpp"
  7. fmha_bwd_traits get_ck_fmha_bwd_traits(const mask_info &mask,
  8. std::string dtype,
  9. int head_size,
  10. bool has_dropout,
  11. bool enable_alibi,
  12. bool deterministic)
  13. {
  14. return fmha_bwd_traits{head_size,
  15. head_size,
  16. dtype,
  17. false, // is_group_mode
  18. mask.type,
  19. enable_alibi ? bias_enum::alibi : bias_enum::no_bias,
  20. false, // has_dbias
  21. has_dropout,
  22. false, // s_randval
  23. deterministic};
  24. }
  25. fmha_bwd_args get_ck_fmha_bwd_args(const mask_info &mask,
  26. // sizes
  27. const int b,
  28. const int seqlen_q,
  29. const int seqlen_k,
  30. const int h,
  31. const int h_k,
  32. const int hdim,
  33. // device pointers
  34. const at::Tensor q,
  35. const at::Tensor k,
  36. const at::Tensor v,
  37. c10::optional<at::Tensor> &alibi_slopes_,
  38. const at::Tensor out,
  39. const at::Tensor softmax_lse,
  40. const at::Tensor dout,
  41. at::Tensor dq_acc,
  42. at::Tensor d,
  43. at::Tensor dq,
  44. at::Tensor dk,
  45. at::Tensor dv,
  46. float softmax_scale,
  47. float p_dropout,
  48. uint64_t drop_seed,
  49. uint64_t drop_offset)
  50. {
  51. // q: (batch_size, seqlen_q, nheads, hdim)
  52. ck_tile::index_t batch_stride_q = q.stride(0);
  53. ck_tile::index_t stride_q = q.stride(1);
  54. ck_tile::index_t nhead_stride_q = q.stride(2);
  55. // k: (batch_size, seqlen_k, nheads_k, hdim)
  56. ck_tile::index_t batch_stride_k = k.stride(0);
  57. ck_tile::index_t stride_k = k.stride(1);
  58. ck_tile::index_t nhead_stride_k = k.stride(2);
  59. // v: (batch_size, seqlen_k, nheads_k, hdim)
  60. ck_tile::index_t batch_stride_v = v.stride(0);
  61. ck_tile::index_t stride_v = v.stride(1);
  62. ck_tile::index_t nhead_stride_v = v.stride(2);
  63. // o: (batch_size, seqlen_q, nheads, hdim)
  64. ck_tile::index_t batch_stride_o = out.stride(0);
  65. ck_tile::index_t stride_o = out.stride(1);
  66. ck_tile::index_t nhead_stride_o = out.stride(2);
  67. // lse: (batch_size, nheads, seqlen_q)
  68. ck_tile::index_t batch_stride_lse = softmax_lse.stride(0);
  69. ck_tile::index_t nhead_stride_lse = softmax_lse.stride(1);
  70. // do: (batch_size, seqlen_q, nheads, hdim)
  71. ck_tile::index_t batch_stride_do = dout.stride(0);
  72. ck_tile::index_t stride_do = dout.stride(1);
  73. ck_tile::index_t nhead_stride_do = dout.stride(2);
  74. // d: (batch_size, nheads, seqlen_q)
  75. // CK assume d share the same stride with lse
  76. // dq: (batch_size, seqlen_q, nheads, hdim)
  77. ck_tile::index_t batch_stride_dq = dq.stride(0);
  78. ck_tile::index_t stride_dq = dq.stride(1);
  79. ck_tile::index_t nhead_stride_dq = dq.stride(2);
  80. // dk_expanded: (batch_size, seqlen_k, nheads, hdim)
  81. ck_tile::index_t batch_stride_dk = dk.stride(0);
  82. ck_tile::index_t stride_dk = dk.stride(1);
  83. ck_tile::index_t nhead_stride_dk = dk.stride(2);
  84. // dv_expanded: (batch_size, seqlen_k, nheads, hdim)
  85. ck_tile::index_t batch_stride_dv = dv.stride(0);
  86. ck_tile::index_t stride_dv = dv.stride(1);
  87. ck_tile::index_t nhead_stride_dv = dv.stride(2);
  88. // dq_acc: (split, batch_size, seqlen_q, nheads, hdim)
  89. ck_tile::index_t split_stride_dq_acc = dq_acc.stride(0);
  90. ck_tile::index_t batch_stride_dq_acc = dq_acc.stride(1);
  91. ck_tile::index_t stride_dq_acc = dq_acc.stride(2);
  92. ck_tile::index_t nhead_stride_dq_acc = dq_acc.stride(3);
  93. float p_undrop = 1.0 - p_dropout;
  94. void *alibi_slopes_ptr = nullptr;
  95. ck_tile::index_t stride_alibi_slopes = 0;
  96. if (alibi_slopes_.has_value()) {
  97. auto alibi_slopes = alibi_slopes_.value();
  98. CHECK_DEVICE(alibi_slopes);
  99. TORCH_CHECK(alibi_slopes.stride(-1) == 1, "ALiBi slopes tensor must have contiguous last dimension");
  100. TORCH_CHECK(alibi_slopes.sizes() == torch::IntArrayRef({h}) || alibi_slopes.sizes() == torch::IntArrayRef({b, h}));
  101. alibi_slopes_ptr = alibi_slopes.data_ptr();
  102. // alibi_slopes:(batch_size, nheads) or (nhead)
  103. stride_alibi_slopes = alibi_slopes.dim() == 2 ? alibi_slopes.stride(0) : 0;
  104. }
  105. return fmha_bwd_args{q.data_ptr(),
  106. k.data_ptr(),
  107. v.data_ptr(),
  108. alibi_slopes_ptr, // bias
  109. out.data_ptr(),
  110. softmax_lse.data_ptr(),
  111. dout.data_ptr(),
  112. d.data_ptr(),
  113. nullptr, // rand_val
  114. dq.data_ptr(),
  115. dk.data_ptr(),
  116. dv.data_ptr(),
  117. nullptr, // dbias
  118. dq_acc.data_ptr(), // dq_acc
  119. nullptr, // seqstart_q
  120. nullptr, // seqstart_k
  121. nullptr, // seqlen_k_ptr
  122. seqlen_q,
  123. seqlen_k,
  124. b,
  125. seqlen_q, // max_seqlen_q
  126. seqlen_k, // max_seqlen_k
  127. hdim, // hdim_q
  128. hdim, // hdim_v
  129. h, // nhead
  130. h_k, // nhead_k
  131. softmax_scale,
  132. stride_q,
  133. stride_k,
  134. stride_v,
  135. stride_alibi_slopes,
  136. stride_o,
  137. 0, // stride_randval
  138. stride_do,
  139. stride_dq_acc,
  140. stride_dq,
  141. stride_dk,
  142. stride_dv,
  143. 0, // stride_dbias, FA without bias
  144. nhead_stride_q,
  145. nhead_stride_k,
  146. nhead_stride_v,
  147. 0, // nhead_stride_bias, FA without bias
  148. nhead_stride_o,
  149. 0, // nhead_stride_randval
  150. nhead_stride_do,
  151. nhead_stride_lse,
  152. nhead_stride_dq_acc,
  153. nhead_stride_dq,
  154. nhead_stride_dk,
  155. nhead_stride_dv,
  156. 0, // nhead_stride_dbias, FA without dbias
  157. batch_stride_q,
  158. batch_stride_k,
  159. batch_stride_v,
  160. 0 , // batch_stride_bias, FA without bias
  161. batch_stride_o,
  162. 0, // batch_stride_randval
  163. batch_stride_do,
  164. batch_stride_lse,
  165. batch_stride_dq_acc,
  166. batch_stride_dq,
  167. batch_stride_dk,
  168. batch_stride_dv,
  169. 0 , // batch_stride_dbias, FA without dbias
  170. split_stride_dq_acc,
  171. mask.left,
  172. mask.right,
  173. static_cast<ck_tile::index_t>(mask.type),
  174. p_dropout,
  175. p_undrop,
  176. {drop_seed, drop_offset}};
  177. }
  178. std::vector<at::Tensor>
  179. mha_bwd(const at::Tensor &dout, // batch_size x seqlen_q x num_heads, x head_size_og
  180. const at::Tensor &q, // batch_size x seqlen_q x num_heads x head_size
  181. const at::Tensor &k, // batch_size x seqlen_k x num_heads_k x head_size
  182. const at::Tensor &v, // batch_size x seqlen_k x num_heads_k x head_size
  183. const at::Tensor &out, // batch_size x seqlen_q x num_heads x head_size
  184. const at::Tensor &softmax_lse, // b x h x seqlen_q
  185. c10::optional<at::Tensor> &dq_, // batch_size x seqlen_q x num_heads x head_size
  186. c10::optional<at::Tensor> &dk_, // batch_size x seqlen_k x num_heads_k x head_size
  187. c10::optional<at::Tensor> &dv_, // batch_size x seqlen_k x num_heads_k x head_size
  188. c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
  189. const float p_dropout, // probability to drop
  190. const float softmax_scale,
  191. const bool is_causal,
  192. int window_size_left,
  193. int window_size_right,
  194. const float /*softcap*/,
  195. const bool deterministic,
  196. c10::optional<at::Generator> gen_,
  197. c10::optional<at::Tensor> &rng_state)
  198. {
  199. #ifdef FLASHATTENTION_DISABLE_BACKWARD
  200. TORCH_CHECK(false, "This flash attention build does not support backward.");
  201. #endif
  202. if (is_causal) { window_size_right = 0; }
  203. bool is_dropout = p_dropout > 0.0;
  204. auto stream = at::cuda::getCurrentHIPStream().stream();
  205. auto q_dtype = q.dtype();
  206. TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
  207. "FlashAttention only support fp16 and bf16 data type");
  208. TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  209. TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
  210. TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
  211. TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
  212. std::string q_dtype_str = q_dtype == torch::kFloat16 ? "fp16" : "bf16";
  213. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
  214. CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
  215. TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  216. TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  217. TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
  218. TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
  219. TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
  220. const auto sizes = q.sizes();
  221. const int batch_size = sizes[0];
  222. const int seqlen_q = sizes[1];
  223. const int num_heads = sizes[2];
  224. const int head_size_og = dout.size(3); // unpadded hdim
  225. const int head_size_8x = sizes[3];
  226. const int seqlen_k = k.size(1);
  227. const int num_heads_k = k.size(2);
  228. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  229. TORCH_CHECK(head_size_8x % 8 == 0, "head_size_8x should be a multiple of 8");
  230. TORCH_CHECK(head_size_8x <= 256, "CK FlashAttention backward only supports head dimension at most 256");
  231. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  232. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  233. TORCH_CHECK(head_size_8x == round_multiple(head_size_og, 8), "head_size_8x must be head_size_og rounded to a multiple of 8");
  234. if (window_size_left >= seqlen_k) { window_size_left = -1; }
  235. if (window_size_right >= seqlen_k) { window_size_right = -1; }
  236. mask_info mask;
  237. if (is_causal) {
  238. std::string mask_identify = "b:" + std::to_string(window_size_left) + "," + "0";
  239. mask = mask_info::decode(mask_identify, seqlen_q, seqlen_k); // casual
  240. }
  241. else if (window_size_left == -1 && window_size_right == -1) {
  242. mask = mask_info::decode("0", seqlen_q, seqlen_k); // no mask
  243. }
  244. else {
  245. // Local is the more general case where window_size_right >= 0 or window_size_left >= 0.
  246. std::string mask_identify = "b:" + std::to_string(window_size_left) + "," + std::to_string(window_size_right);
  247. mask = mask_info::decode(mask_identify, seqlen_q, seqlen_k); // local
  248. }
  249. // q, k, v, out had been padded in mha_fwd
  250. // dq_, dk_, dv_ are also padded tensor
  251. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_8x);
  252. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size_8x);
  253. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size_8x);
  254. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_8x);
  255. CHECK_SHAPE(dout, batch_size, seqlen_q, num_heads, head_size_og);
  256. at::Tensor dq, dk, dv;
  257. if (dq_.has_value()) {
  258. dq = dq_.value();
  259. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  260. CHECK_DEVICE(dq);
  261. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  262. CHECK_SHAPE(dq, batch_size, seqlen_q, num_heads, head_size_8x);
  263. } else {
  264. dq = torch::empty_like(q);
  265. }
  266. if (dk_.has_value()) {
  267. dk = dk_.value();
  268. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  269. CHECK_DEVICE(dk);
  270. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  271. CHECK_SHAPE(dk, batch_size, seqlen_k, num_heads_k, head_size_8x);
  272. } else {
  273. dk = torch::empty_like(k);
  274. }
  275. if (dv_.has_value()) {
  276. dv = dv_.value();
  277. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  278. CHECK_DEVICE(dv);
  279. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  280. CHECK_SHAPE(dv, batch_size, seqlen_k, num_heads_k, head_size_8x);
  281. } else {
  282. dv = torch::empty_like(v);
  283. }
  284. at::Tensor dout_padded;
  285. if (head_size_og % 8 != 0) {
  286. dout_padded = torch::nn::functional::pad(dout, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
  287. } else {
  288. dout_padded = dout;
  289. }
  290. // Cast to char to avoid compiler warning about narrowing
  291. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  292. auto opts = q.options();
  293. auto softmax_d = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  294. at::Tensor dq_accum;
  295. if (!deterministic) {
  296. dq_accum = torch::zeros({1, batch_size, seqlen_q, num_heads, head_size_8x}, opts.dtype(at::kFloat));
  297. } else {
  298. const ck_tile::index_t kN0 = head_size_8x <= 128 ? 128 : 64;
  299. const ck_tile::index_t nsplits = ck_tile::integer_divide_ceil(seqlen_k, kN0);
  300. dq_accum = torch::zeros({nsplits, batch_size, seqlen_q, num_heads, head_size_8x}, opts.dtype(at::kFloat));
  301. }
  302. at::Tensor dk_expanded, dv_expanded;
  303. if (num_heads_k != num_heads) { // MQA / GQA
  304. dk_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size_8x}, opts);
  305. dv_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size_8x}, opts);
  306. } else {
  307. dk_expanded = dk;
  308. dv_expanded = dv;
  309. }
  310. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  311. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  312. uint64_t drop_seed = 1, drop_offset = 0;
  313. int64_t counter_offset = batch_size * num_heads * ck_tile::get_warp_size();
  314. if (rng_state.has_value()) {
  315. uint64_t* d = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
  316. drop_seed = d[0];
  317. drop_offset = d[1];
  318. } else if(is_dropout) {
  319. // See Note [Acquire lock when using random generators]
  320. std::lock_guard<std::mutex> lock(gen->mutex_);
  321. auto philox_args = gen->philox_cuda_state(counter_offset);
  322. std::tie(drop_seed, drop_offset) = flash::unpack(philox_args);
  323. }
  324. if (seqlen_q > 0) {
  325. ck_tile::stream_config stream_config{stream};
  326. auto traits =
  327. get_ck_fmha_bwd_traits(mask, q_dtype_str, head_size_8x, is_dropout, alibi_slopes_.has_value(), deterministic);
  328. auto args =
  329. get_ck_fmha_bwd_args(
  330. mask,
  331. batch_size,
  332. seqlen_q,
  333. seqlen_k,
  334. num_heads,
  335. num_heads_k,
  336. head_size_8x,
  337. q,
  338. k,
  339. v,
  340. alibi_slopes_,
  341. out,
  342. softmax_lse,
  343. dout_padded,
  344. dq_accum,
  345. softmax_d,
  346. dq,
  347. dk_expanded,
  348. dv_expanded,
  349. softmax_scale,
  350. p_dropout,
  351. drop_seed,
  352. drop_offset);
  353. float t = fmha_bwd(traits, args, stream_config);
  354. TORCH_CHECK(t >= 0, "invalid argument for fmha_bwd");
  355. } else {
  356. // If seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  357. dk_expanded.zero_();
  358. dv_expanded.zero_();
  359. softmax_d.zero_();
  360. }
  361. // For MQA/GQA we need to sum dK and dV across the groups
  362. if (num_heads_k != num_heads) {
  363. at::sum_out(dk, at::reshape(dk_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size_8x}), {3});
  364. at::sum_out(dv, at::reshape(dv_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size_8x}), {3});
  365. }
  366. if (head_size_og % 8 != 0) {
  367. dq = dq.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  368. dk = dk.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  369. dv = dv.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
  370. }
  371. return { dq, dk, dv, softmax_d };
  372. }