1
0

mha_bwd.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 multiple_of(head_size, 8)
  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 = sizes[3];
  225. const int seqlen_k = k.size(1);
  226. const int num_heads_k = k.size(2);
  227. TORCH_CHECK(batch_size > 0, "batch size must be positive");
  228. TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
  229. TORCH_CHECK(head_size <= 256, "CK FlashAttention backward only supports head dimension at most 256");
  230. TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
  231. if (window_size_left >= seqlen_k) { window_size_left = -1; }
  232. if (window_size_right >= seqlen_k) { window_size_right = -1; }
  233. mask_info mask;
  234. if (is_causal) {
  235. std::string mask_identify = "b:" + std::to_string(window_size_left) + "," + "0";
  236. mask = mask_info::decode(mask_identify, seqlen_q, seqlen_k); // casual
  237. }
  238. else if (window_size_left == -1 && window_size_right == -1) {
  239. mask = mask_info::decode("0", seqlen_q, seqlen_k); // no mask
  240. }
  241. else {
  242. // Local is the more general case where window_size_right >= 0 or window_size_left >= 0.
  243. std::string mask_identify = "b:" + std::to_string(window_size_left) + "," + std::to_string(window_size_right);
  244. mask = mask_info::decode(mask_identify, seqlen_q, seqlen_k); // local
  245. }
  246. // q, k, v, out had been padded in mha_fwd
  247. // dq_, dk_, dv_ are also padded tensor
  248. CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size);
  249. CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size);
  250. CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size);
  251. CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size);
  252. CHECK_SHAPE(dout, batch_size, seqlen_q, num_heads, head_size);
  253. at::Tensor dq, dk, dv;
  254. if (dq_.has_value()) {
  255. dq = dq_.value();
  256. TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
  257. CHECK_DEVICE(dq);
  258. TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
  259. CHECK_SHAPE(dq, batch_size, seqlen_q, num_heads, head_size);
  260. } else {
  261. dq = torch::empty_like(q);
  262. }
  263. if (dk_.has_value()) {
  264. dk = dk_.value();
  265. TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
  266. CHECK_DEVICE(dk);
  267. TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
  268. CHECK_SHAPE(dk, batch_size, seqlen_k, num_heads_k, head_size);
  269. } else {
  270. dk = torch::empty_like(k);
  271. }
  272. if (dv_.has_value()) {
  273. dv = dv_.value();
  274. TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
  275. CHECK_DEVICE(dv);
  276. TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
  277. CHECK_SHAPE(dv, batch_size, seqlen_k, num_heads_k, head_size);
  278. } else {
  279. dv = torch::empty_like(v);
  280. }
  281. // Cast to char to avoid compiler warning about narrowing
  282. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  283. auto opts = q.options();
  284. auto softmax_d = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
  285. at::Tensor dq_accum;
  286. if (!deterministic) {
  287. dq_accum = torch::zeros({1, batch_size, seqlen_q, num_heads, head_size}, opts.dtype(at::kFloat));
  288. } else {
  289. const ck_tile::index_t kN0 = head_size <= 128 ? 128 : 64;
  290. const ck_tile::index_t nsplits = ck_tile::integer_divide_ceil(seqlen_k, kN0);
  291. dq_accum = torch::zeros({nsplits, batch_size, seqlen_q, num_heads, head_size}, opts.dtype(at::kFloat));
  292. }
  293. at::Tensor dk_expanded, dv_expanded;
  294. if (num_heads_k != num_heads) { // MQA / GQA
  295. dk_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  296. dv_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
  297. } else {
  298. dk_expanded = dk;
  299. dv_expanded = dv;
  300. }
  301. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  302. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  303. uint64_t drop_seed = 1, drop_offset = 0;
  304. int64_t counter_offset = batch_size * num_heads * ck_tile::get_warp_size();
  305. if (rng_state.has_value()) {
  306. uint64_t* d = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
  307. drop_seed = d[0];
  308. drop_offset = d[1];
  309. } else if(is_dropout) {
  310. // See Note [Acquire lock when using random generators]
  311. std::lock_guard<std::mutex> lock(gen->mutex_);
  312. auto philox_args = gen->philox_cuda_state(counter_offset);
  313. std::tie(drop_seed, drop_offset) = flash::unpack(philox_args);
  314. }
  315. if (seqlen_q > 0) {
  316. ck_tile::stream_config stream_config{stream};
  317. auto traits =
  318. get_ck_fmha_bwd_traits(mask, q_dtype_str, head_size, is_dropout, alibi_slopes_.has_value(), deterministic);
  319. auto args =
  320. get_ck_fmha_bwd_args(
  321. mask,
  322. batch_size,
  323. seqlen_q,
  324. seqlen_k,
  325. num_heads,
  326. num_heads_k,
  327. head_size,
  328. q,
  329. k,
  330. v,
  331. alibi_slopes_,
  332. out,
  333. softmax_lse,
  334. dout,
  335. dq_accum,
  336. softmax_d,
  337. dq,
  338. dk_expanded,
  339. dv_expanded,
  340. softmax_scale,
  341. p_dropout,
  342. drop_seed,
  343. drop_offset);
  344. float t = fmha_bwd(traits, args, stream_config);
  345. TORCH_CHECK(t >= 0, "invalid argument for fmha_bwd");
  346. } else {
  347. // If seqlen_q == 0, then we have an empty tensor. We need to set the output to 0.
  348. dk_expanded.zero_();
  349. dv_expanded.zero_();
  350. softmax_d.zero_();
  351. }
  352. // For MQA/GQA we need to sum dK and dV across the groups
  353. if (num_heads_k != num_heads) {
  354. at::sum_out(dk, at::reshape(dk_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  355. at::sum_out(dv, at::reshape(dv_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
  356. }
  357. return { dq, dk, dv, softmax_d };
  358. }