1
0

mha_varlen_bwd.cpp 18 KB

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