mainloop_bwd_sm80.hpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. /******************************************************************************
  2. * Copyright (c) 2024, Tri Dao.
  3. ******************************************************************************/
  4. #pragma once
  5. #include <cutlass/cutlass.h>
  6. #include <cutlass/array.h>
  7. #include <cutlass/numeric_types.h>
  8. #include <cutlass/numeric_conversion.h>
  9. #include "cute/tensor.hpp"
  10. #include "seqlen.h"
  11. #include "mask.h"
  12. #include "mask.h"
  13. #include "softmax.h"
  14. #include "utils.h"
  15. namespace flash {
  16. using namespace cute;
  17. template <int Stages, int Stages_dO, class TileShape_MNK_, class Element_, class ElementAccum_, class ArchTag_,
  18. bool Is_causal_, bool Is_local_, bool Has_softcap_, bool Varlen_, bool Deterministic,
  19. bool SdP_swapAB_, bool dKV_swapAB_, bool dQ_swapAB_,
  20. int NumMmaWarpGroups=2, int AtomLayoutMSdP=1, int AtomLayoutNdKV=8, int AtomLayoutMdQ=1,
  21. bool V_in_regs=false>
  22. struct CollectiveMainloopBwdSm80 {
  23. static constexpr int kStages = Stages;
  24. static constexpr int kStages_dO = Stages_dO;
  25. static_assert(kStages >= kStages_dO);
  26. using TileShape_MNK = TileShape_MNK_;
  27. using Element = Element_;
  28. using ElementAccum = ElementAccum_;
  29. using ArchTag = ArchTag_;
  30. static constexpr bool Is_causal = Is_causal_;
  31. static constexpr bool Is_local = Is_local_;
  32. static constexpr bool Has_softcap = Has_softcap_;
  33. static constexpr bool Varlen = Varlen_;
  34. static constexpr int NumMmaWarps = NumMmaWarpGroups * cutlass::NumWarpsPerWarpGroup;
  35. static constexpr bool SdP_swapAB = SdP_swapAB_;
  36. static constexpr bool dKV_swapAB = dKV_swapAB_;
  37. static constexpr bool dQ_swapAB = dQ_swapAB_;
  38. static constexpr bool Q_dO_same_stages = kStages == kStages_dO;
  39. static constexpr int kBlockM = get<0>(TileShape_MNK{});
  40. static constexpr int kBlockN = get<1>(TileShape_MNK{});
  41. static constexpr int kHeadDim = get<2>(TileShape_MNK{});
  42. using SeqlenInfo_t = flash::SeqlenInfoQK<Varlen, kBlockM>;
  43. using BlockMN_t = flash::BlockMN<SeqlenInfo_t, kBlockM, kBlockN, Is_causal, Is_local>;
  44. static_assert(ArchTag::kMinComputeCapability >= 80);
  45. static constexpr bool Has_cp_async = ArchTag::kMinComputeCapability >= 80;
  46. static constexpr int NumMmaThreads = NumMmaWarps * cutlass::NumThreadsPerWarp;
  47. static constexpr int NumProducerThreads = NumMmaThreads; // For compatibility with TileScheduler
  48. using MMA_Atom_Arch = std::conditional_t<
  49. ArchTag::kMinComputeCapability >= 80,
  50. std::conditional_t<
  51. std::is_same_v<Element, cutlass::half_t>,
  52. MMA_Atom<SM80_16x8x16_F32F16F16F32_TN>,
  53. MMA_Atom<SM80_16x8x16_F32BF16BF16F32_TN>
  54. >,
  55. MMA_Atom<SM75_16x8x8_F32F16F16F32_TN>
  56. >;
  57. static_assert(NumMmaWarps % AtomLayoutMSdP == 0);
  58. static_assert(NumMmaWarps % AtomLayoutNdKV == 0);
  59. static_assert(NumMmaWarps % AtomLayoutMdQ == 0);
  60. static constexpr bool Mma_dKV_is_RS = AtomLayoutMSdP == 1 && AtomLayoutNdKV == NumMmaWarps && SdP_swapAB && !dKV_swapAB;
  61. static constexpr bool Mma_dQ_is_RS = AtomLayoutMSdP == NumMmaWarps && AtomLayoutMdQ == NumMmaWarps && !SdP_swapAB && !dQ_swapAB; // If dQ_swapAB we can't use RS
  62. using AtomLayoutSdP = std::conditional_t<
  63. !SdP_swapAB,
  64. Layout<Shape<Int<AtomLayoutMSdP>, Int<NumMmaWarps / AtomLayoutMSdP>, _1>>,
  65. Layout<Shape<Int<NumMmaWarps / AtomLayoutMSdP>, Int<AtomLayoutMSdP>, _1>>
  66. >;
  67. static constexpr bool MmaSdPEvenN = ((!SdP_swapAB ? kBlockN : kBlockM) / size<1>(AtomLayoutSdP{})) % 16 == 0;
  68. using TiledMmaSdP = TiledMMA<
  69. MMA_Atom_Arch,
  70. AtomLayoutSdP,
  71. Tile<Int<16 * CUTE_STATIC_V(size<0>(AtomLayoutSdP{}))>, Int<(MmaSdPEvenN ? 16 : 8) * CUTE_STATIC_V(size<1>(AtomLayoutSdP{}))>, _16>>;
  72. using AtomLayoutdKV = std::conditional_t<
  73. !dKV_swapAB,
  74. Layout<Shape<Int<AtomLayoutNdKV>, Int<NumMmaWarps / AtomLayoutNdKV>, _1>>,
  75. Layout<Shape<Int<NumMmaWarps / AtomLayoutNdKV>, Int<AtomLayoutNdKV>, _1>>
  76. >;
  77. static constexpr bool MmadKVEvenN = ((!dKV_swapAB ? kHeadDim : kBlockN) / size<1>(AtomLayoutdKV{})) % 16 == 0;
  78. using TiledMmadKV = TiledMMA<
  79. MMA_Atom_Arch,
  80. AtomLayoutdKV,
  81. Tile<Int<16 * CUTE_STATIC_V(size<0>(AtomLayoutdKV{}))>, Int<(MmadKVEvenN ? 16 : 8) * CUTE_STATIC_V(size<1>(AtomLayoutdKV{}))>, _16>>;
  82. using AtomLayoutdQ = std::conditional_t<
  83. !dQ_swapAB,
  84. Layout<Shape<Int<AtomLayoutMdQ>, Int<NumMmaWarps / AtomLayoutMdQ>, _1>>,
  85. Layout<Shape<Int<NumMmaWarps / AtomLayoutMdQ>, Int<AtomLayoutMdQ>, _1>>
  86. >;
  87. static constexpr bool MmadQEvenN = ((!dQ_swapAB ? kHeadDim : kBlockM) / size<1>(AtomLayoutdQ{})) % 16 == 0;
  88. using TiledMmadQ = TiledMMA<
  89. MMA_Atom_Arch,
  90. AtomLayoutdQ,
  91. Tile<Int<16 * CUTE_STATIC_V(size<0>(AtomLayoutdQ{}))>, Int<(MmadQEvenN ? 16 : 8) * CUTE_STATIC_V(size<1>(AtomLayoutdQ{}))>, _16>>;
  92. static constexpr int kGmemElemsPerLoad = sizeof(cute::uint128_t) / sizeof(Element);
  93. static_assert(kHeadDim % kGmemElemsPerLoad == 0, "Headdim must be a multiple of kGmemElemsPerLoad");
  94. // We want each "row" to have 64 elements (128 bytes, i.e. 1 cache line). E.g. if hdim=128, we want each
  95. // thread to have 4 loads in the M direction and 2 vectorized load in the K direction.
  96. static constexpr int kBytePerRow = kHeadDim * sizeof(Element);
  97. static constexpr int kBlockKGmem = (kBytePerRow % 128 == 0 ? 128 : (kBytePerRow % 64 == 0 ? 64 : 32)) / sizeof(Element);
  98. static constexpr int kSwizzle = kBlockKGmem == 128 ? 4 : (kBlockKGmem == 64 ? 3 : (kBlockKGmem == 32 ? 2 : 1));
  99. static constexpr int kSwizzleBase = sizeof(Element) == 4 ? 2 : (sizeof(Element) == 2 ? 3 : 4);
  100. // We need to accommodate both Q and Q^T (and dO and dO^T) in shared memory.
  101. // Q & dO are used in the SdP Mma and Q^T and dO^T are used in the dKV Mma.
  102. // Since this is GMMA::Major::K, the M dimension (kBlockM) doesn't matter for the layout, only the K dimension
  103. // changes the layout.
  104. using SmemLayoutAtomQdO = decltype(
  105. composition(Swizzle<kSwizzle, kSwizzleBase, kSwizzleBase>{},
  106. Layout<Shape<_8, Int<kBlockKGmem>>,
  107. Stride<Int<kBlockKGmem>, _1>>{}));
  108. using SmemLayoutQ =
  109. decltype(tile_to_shape(SmemLayoutAtomQdO{},
  110. make_shape(shape<0>(TileShape_MNK{}), shape<2>(TileShape_MNK{}), Int<kStages>{})));
  111. using SmemLayoutdO =
  112. decltype(tile_to_shape(SmemLayoutAtomQdO{},
  113. make_shape(shape<0>(TileShape_MNK{}), shape<2>(TileShape_MNK{}), Int<kStages_dO>{})));
  114. using SmemLayoutAtomKV = decltype(
  115. composition(Swizzle<kSwizzle, kSwizzleBase, kSwizzleBase>{},
  116. // TODO: FA2 has a slightly different layout, does it matter?
  117. Layout<Shape<_8, Int<kBlockKGmem>>,
  118. Stride<Int<kBlockKGmem>, _1>>{}));
  119. using SmemLayoutK = decltype(tile_to_shape(SmemLayoutAtomKV{}, select<1, 2>(TileShape_MNK{})));
  120. using SmemLayoutV = decltype(tile_to_shape(SmemLayoutAtomKV{}, select<1, 2>(TileShape_MNK{})));
  121. // TD [2023-03-19]: Idk why kPBlockN = 16 and kSwizzlePdS=3 is the fastest.
  122. static constexpr int kPBlockN = kBlockN % 64 == 0 ? 64 : (kBlockN % 32 == 0 ? 32 : 16);
  123. static_assert(kPBlockN == 16 || kPBlockN == 32 || kPBlockN == 64);
  124. // static constexpr int kSwizzlePdS = kPBlockN == 16 ? 1 : (kPBlockN == 32 ? 2 : 3);
  125. static constexpr int kSwizzlePdS = 3;
  126. using SmemLayoutAtomPdS = decltype(
  127. composition(Swizzle<kSwizzlePdS, kSwizzleBase, kSwizzleBase>{},
  128. Layout<Shape<Int<kBlockM>, Int<kPBlockN>>,
  129. Stride<Int<kPBlockN>, _1>>{}));
  130. using SmemLayoutPdS = decltype(tile_to_shape(
  131. SmemLayoutAtomPdS{},
  132. make_shape(Int<kBlockM>{}, Int<kBlockN>{})));
  133. // We set stride to be multiple of 64 so that if ShuffleLSE, even if threads read from sLSE but out of bounds,
  134. // it's still a valid smem address.
  135. using SmemLayoutLSE = cute::Layout<cute::Shape<Int<kBlockM>, Int<kStages>>, cute::Stride<_1, Int<cute::round_up(kBlockM, 64)>>>;
  136. using SmemLayoutLSEMma = std::conditional_t<
  137. SdP_swapAB,
  138. cute::Layout<cute::Shape<Int<kBlockN>, Int<kBlockM>, Int<kStages>>, cute::Stride<_0, _1, Int<cute::round_up(kBlockM, 64)>>>,
  139. cute::Layout<cute::Shape<Int<kBlockM>, Int<kBlockN>, Int<kStages>>, cute::Stride<_1, _0, Int<cute::round_up(kBlockM, 64)>>>
  140. >;
  141. // Note this is the transpose in terms of the view, not in terms of memory.
  142. using SmemLayoutQt =
  143. decltype(cute::composition(SmemLayoutQ{},
  144. make_layout(make_shape(get<2>(TileShape_MNK{}), get<0>(TileShape_MNK{}), Int<kStages>{}),
  145. make_stride(Int<kBlockM>{}, _1{}, Int<kBlockM * kHeadDim>{}))));
  146. using SmemLayoutdOt =
  147. decltype(cute::composition(SmemLayoutdO{},
  148. make_layout(make_shape(get<2>(TileShape_MNK{}), get<0>(TileShape_MNK{}), Int<kStages_dO>{}),
  149. make_stride(Int<kBlockM>{}, _1{}, Int<kBlockM * kHeadDim>{}))));
  150. using SmemLayoutKt =
  151. decltype(cute::composition(SmemLayoutK{},
  152. make_layout(make_shape(get<2>(TileShape_MNK{}), get<1>(TileShape_MNK{})),
  153. make_stride(Int<kBlockN>{}, _1{}))));
  154. using SmemLayoutPdSt =
  155. decltype(cute::composition(SmemLayoutPdS{},
  156. make_layout(make_shape(Int<kBlockN>{}, Int<kBlockM>{}),
  157. make_stride(Int<kBlockM>{}, _1{}))));
  158. // Thread layout, 256 or 384 threads per row
  159. using R2SLayoutAtomdQaccum = Layout<Shape<Int<NumMmaThreads>>>;
  160. using R2STiledCopydQaccum = decltype(make_tiled_copy(Copy_Atom<AutoVectorizingCopyWithAssumedAlignment<128>, ElementAccum>{}, R2SLayoutAtomdQaccum{},
  161. Layout<Shape < _1>>{})); // Val layout, 1 vals per store
  162. using SmemCopyAtom = Copy_Atom<SM75_U32x4_LDSM_N, Element>;
  163. using SmemCopyAtomTransposed = Copy_Atom<SM75_U16x8_LDSM_T, Element>;
  164. // For the case where the N dimension of MmaSdP is divisible by 8 but not by 16
  165. using SmemCopyAtomHalf = Copy_Atom<SM75_U32x2_LDSM_N, Element>;
  166. // For the case where the N dimension of MmadQ is divisible by 8 but not by 16
  167. using SmemCopyAtomTransposedHalf = Copy_Atom<SM75_U16x4_LDSM_T, Element>;
  168. // If !SdP_swapAB, the accum registers hold P / dS, otherwise they hold Pt / dSt.
  169. // If PdS_major is MN, then we need to "transpose" the write.
  170. // TODO: check this write
  171. using R2SCopyAtomPdS = Copy_Atom<AutoVectorizingCopyWithAssumedAlignment<128>, Element>;
  172. // We use CACHEGLOBAL instead of CACHEALWAYS for both Q and K/V, since we won't be reading
  173. // from the same address by the same threadblock. This is slightly faster.
  174. using GmemCopyStruct = std::conditional_t<
  175. Has_cp_async,
  176. SM80_CP_ASYNC_CACHEGLOBAL_ZFILL<cute::uint128_t>,
  177. AutoVectorizingCopyWithAssumedAlignment<128>
  178. >;
  179. using GmemCopyAtom = Copy_Atom<GmemCopyStruct, Element>;
  180. static constexpr int kGmemThreadsPerRow = kBlockKGmem / kGmemElemsPerLoad;
  181. static_assert(NumMmaThreads % kGmemThreadsPerRow == 0, "NumMmaThreads must be a multiple of kGmemThreadsPerRow");
  182. using GmemLayoutAtom = Layout<Shape <Int<NumMmaThreads / kGmemThreadsPerRow>, Int<kGmemThreadsPerRow>>,
  183. Stride<Int<kGmemThreadsPerRow>, _1>>;
  184. using GmemTiledCopyQKV = decltype(
  185. make_tiled_copy(GmemCopyAtom{},
  186. GmemLayoutAtom{},
  187. Layout<Shape<_1, Int<kGmemElemsPerLoad>>>{})); // Val layout, 8 or 16 vals per read
  188. using GmemCopyAtomLSE = Copy_Atom<GmemCopyStruct, float>;
  189. using GmemLayoutAtomLSE = Layout<Shape<Int<NumMmaThreads>>>;
  190. using GmemTiledCopyLSE = decltype(make_tiled_copy(GmemCopyAtomLSE{}, GmemLayoutAtomLSE{},
  191. Layout<Shape<_4>>{})); // Val layout, 4 vals per store
  192. // So that we don't have to check if we overshot kBlockM when we load Q
  193. // static_assert(kBlockM % CUTE_STATIC_V(shape<0>(GmemLayoutAtom{})) == 0);
  194. using ShapeQKV = cute::Shape<int32_t, int32_t, int32_t, int32_t>; // (seqlen, d, head, batch)
  195. using StrideQKV = cute::Stride<int64_t, _1, int64_t, int64_t>;
  196. using ShapeLSE = cute::Shape<int32_t, int32_t, int32_t>; // (seqlen, head, batch)
  197. using StrideLSE = cute::Stride<_1, int64_t, int64_t>; // (seqlen, head, batch)
  198. using ShapedQaccum = cute::Shape<int32_t, int32_t, int32_t>; // (seqlen_q * d, head, batch)
  199. using StridedQaccum = cute::Stride<_1, int64_t, int64_t>;
  200. // These are tuned for speed. They don't affect correctness.
  201. // We have separate iterations with causal masking. Not necessary for hdim 128 but for hdim 64
  202. // this helps quite a bit to not have to do causal masking for most of the iterations.
  203. // For hdim 192, separating masking iterations results in register spills.
  204. // static constexpr bool SeparateMaskingIterations = kHeadDim <= 64;
  205. static constexpr bool SeparateMaskingIterations = false;
  206. // Do we keep the LSE and dPsum in each thread, or split them across 8 threads that share them and then
  207. // shuffle to get the value whenever we need? This can reduce register pressure when SdP_swapAB, where each
  208. // thread needs to keep statistics for (kBlockM / 4) rows. If !SdP_swapAB, each thread only needs to keep
  209. // statistic for 2 rows.
  210. // static constexpr bool ShuffleLSE = SdP_swapAB && kHeadDim <= 64;
  211. // static constexpr bool ShuffledPsum = SdP_swapAB && kHeadDim <= 64;
  212. static constexpr bool ShuffleLSE = SdP_swapAB && false;
  213. static constexpr bool ShuffledPsum = SdP_swapAB && false;
  214. static constexpr bool Share_QV_Smem = V_in_regs;
  215. using SmemP_t = std::conditional_t<Mma_dKV_is_RS, cute::array<Element, 0>, cute::array_aligned<Element, cute::cosize_v<SmemLayoutPdS>>>;
  216. struct TensorStorageSharedQV : cute::aligned_struct<128> {
  217. cute::array_aligned<Element, cute::cosize_v<SmemLayoutK>> smem_k;
  218. union {
  219. cute::array_aligned<Element, cute::cosize_v<SmemLayoutV>> smem_v;
  220. cute::array_aligned<Element, cute::cosize_v<SmemLayoutQ>> smem_q;
  221. };
  222. cute::array_aligned<Element, cute::cosize_v<SmemLayoutdO>> smem_do;
  223. cute::array_aligned<ElementAccum, cute::cosize_v<SmemLayoutLSE>, 128> smem_lse;
  224. cute::array_aligned<ElementAccum, cute::cosize_v<SmemLayoutLSE>, 128> smem_dpsum;
  225. SmemP_t smem_p;
  226. cute::array_aligned<Element, cute::cosize_v<SmemLayoutPdS>> smem_ds;
  227. };
  228. struct TensorStorageSeparateQV : cute::aligned_struct<128> {
  229. cute::array_aligned<Element, cute::cosize_v<SmemLayoutK>> smem_k;
  230. cute::array_aligned<Element, cute::cosize_v<SmemLayoutV>> smem_v;
  231. cute::array_aligned<Element, cute::cosize_v<SmemLayoutQ>> smem_q;
  232. cute::array_aligned<Element, cute::cosize_v<SmemLayoutdO>> smem_do;
  233. cute::array_aligned<ElementAccum, cute::cosize_v<SmemLayoutLSE>, 128> smem_lse;
  234. cute::array_aligned<ElementAccum, cute::cosize_v<SmemLayoutLSE>, 128> smem_dpsum;
  235. SmemP_t smem_p;
  236. cute::array_aligned<Element, cute::cosize_v<SmemLayoutPdS>> smem_ds;
  237. };
  238. using TensorStorage = std::conditional_t<Share_QV_Smem, TensorStorageSharedQV, TensorStorageSeparateQV>;
  239. // Host side kernel arguments
  240. struct Arguments {
  241. Element const* const ptr_Q;
  242. ShapeQKV const shape_Q;
  243. StrideQKV const stride_Q;
  244. Element const* const ptr_K;
  245. ShapeQKV const shape_K;
  246. StrideQKV const stride_K;
  247. Element const* const ptr_V;
  248. StrideQKV const stride_V;
  249. Element const* const ptr_dO;
  250. StrideQKV const stride_dO;
  251. ElementAccum* const ptr_dQaccum;
  252. ShapedQaccum const shape_dQaccum;
  253. StridedQaccum const stride_dQaccum;
  254. float const* const ptr_LSE_log2;
  255. ShapeLSE const shape_LSE;
  256. StrideLSE const stride_LSE_log2;
  257. float const* const ptr_dPsum;
  258. StrideLSE const stride_dPsum;
  259. float const softmax_scale;
  260. int const window_size_left, window_size_right;
  261. float const softcap_val;
  262. int const num_batch;
  263. int* const dq_semaphore;
  264. int const* const cu_seqlens_q = nullptr;
  265. int const* const cu_seqlens_k = nullptr;
  266. int const* const seqused_q = nullptr;
  267. int const* const seqused_k = nullptr;
  268. };
  269. // Device side kernel params
  270. struct Params {
  271. Element const* const ptr_Q;
  272. ShapeQKV const shape_Q;
  273. StrideQKV const stride_Q;
  274. Element const* const ptr_K;
  275. ShapeQKV const shape_K;
  276. StrideQKV const stride_K;
  277. Element const* const ptr_V;
  278. StrideQKV const stride_V;
  279. Element const* const ptr_dO;
  280. StrideQKV const stride_dO;
  281. ElementAccum* const ptr_dQaccum;
  282. ShapedQaccum const shape_dQaccum;
  283. StridedQaccum stride_dQaccum;
  284. cutlass::FastDivmod qhead_per_khead_divmod;
  285. float const* const ptr_LSE_log2;
  286. ShapeLSE const shape_LSE;
  287. StrideLSE const stride_LSE_log2;
  288. float const* const ptr_dPsum;
  289. StrideLSE const stride_dPsum;
  290. float const softmax_scale, softmax_scale_log2;
  291. int const window_size_left, window_size_right;
  292. float const softcap_val;
  293. int const num_batch;
  294. int *const dq_semaphore;
  295. int const *const cu_seqlens_q = nullptr;
  296. int const *const cu_seqlens_k = nullptr;
  297. int const *const seqused_q = nullptr;
  298. int const *const seqused_k = nullptr;
  299. };
  300. static Params
  301. to_underlying_arguments(Arguments const& args) {
  302. if constexpr (Deterministic) { assert(args.dq_semaphore != nullptr); }
  303. // If there's tanh softcapping, we do tanh(scores * softmax_scale / softcap_val) * softcap_val.
  304. // Right after this, we multiply by log2(e) before applying exp2.
  305. // To reduce the number of instructions, we instead pre-multiply softmax_scale / softcap_val
  306. // (assigning it to params.softcap_val) and pre-multiply softcap_val * log2(e)
  307. // (assigning it to params.softmax_scale_log2).
  308. // In the backward, we need to multiply by
  309. // (1 - tanh^2) * softmax_scale / softcap_val * softcap_val = (1 - tanh^2) * softmax_scale.
  310. // Instead we multiply by (1 - tanh^2) and multiply dK and dV by params.softmax_scale
  311. // (the original softmax_scale) at the end.
  312. return {args.ptr_Q, args.shape_Q, args.stride_Q,
  313. args.ptr_K, args.shape_K, args.stride_K,
  314. args.ptr_V, args.stride_V,
  315. args.ptr_dO, args.stride_dO,
  316. args.ptr_dQaccum, args.shape_dQaccum, args.stride_dQaccum,
  317. cutlass::FastDivmod(cute::ceil_div(get<2>(args.shape_Q), get<2>(args.shape_K))),
  318. args.ptr_LSE_log2, args.shape_LSE, args.stride_LSE_log2, args.ptr_dPsum, args.stride_dPsum,
  319. args.softmax_scale,
  320. !Has_softcap ? float(args.softmax_scale * M_LOG2E) : float(args.softcap_val * M_LOG2E),
  321. args.window_size_left, args.window_size_right,
  322. !Has_softcap ? 0.f : args.softmax_scale / args.softcap_val,
  323. args.num_batch, args.dq_semaphore,
  324. args.cu_seqlens_q, args.cu_seqlens_k, args.seqused_q, args.seqused_k};
  325. }
  326. template <typename SharedStorage, typename FrgTensordKV>
  327. CUTLASS_DEVICE bool
  328. mma(Params const& params,
  329. FrgTensordKV& tdKrdK,
  330. FrgTensordKV& tdVrdV,
  331. int thread_idx,
  332. cute::tuple<int32_t, int32_t, int32_t> block_coord,
  333. SharedStorage& shared_storage
  334. ) {
  335. static_assert(is_rmem<FrgTensordKV>::value, "dK and dV tensor must be rmem resident.");
  336. int n_block = get<0>(block_coord);
  337. int bidh = get<1>(block_coord);
  338. int bidb = get<2>(block_coord);
  339. SeqlenInfo_t seqlen_info{
  340. bidb, get<0>(params.shape_Q), size<0>(params.shape_K),
  341. params.cu_seqlens_q, params.cu_seqlens_k, params.seqused_q, params.seqused_k
  342. };
  343. auto m_block_min_max = BlockMN_t::get_m_block_min_max(
  344. seqlen_info, n_block, bidb,
  345. params.window_size_left, params.window_size_right, 0 /*sink_token_length*/);
  346. int const m_block_min = get<0>(m_block_min_max);
  347. int const m_block_max = get<1>(m_block_min_max);
  348. // It's possible to have m_block_max <= m_block_min. Exit early
  349. if constexpr (Is_causal || Is_local || Varlen) {
  350. if (m_block_max <= m_block_min) { return false; }
  351. }
  352. Tensor sQ = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_q.data()), SmemLayoutQ{});
  353. Tensor sdO = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_do.data()), SmemLayoutdO{});
  354. Tensor sK = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_k.data()), SmemLayoutK{});
  355. Tensor sV = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_v.data()), SmemLayoutV{});
  356. Tensor sQt = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_q.data()), SmemLayoutQt{});
  357. Tensor sdOt = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_do.data()), SmemLayoutdOt{});
  358. Tensor sKt = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_k.data()), SmemLayoutKt{});
  359. Tensor sP = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_p.data()), SmemLayoutPdS{});
  360. Tensor sPt = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_p.data()), SmemLayoutPdSt{});
  361. Tensor sdS = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_ds.data()), SmemLayoutPdS{});
  362. Tensor sdSt = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_ds.data()), SmemLayoutPdSt{});
  363. Tensor sLSE = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_lse.data()), SmemLayoutLSE{});
  364. Tensor sdPsum = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_dpsum.data()), SmemLayoutLSE{});
  365. Tensor sLSEMma = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_lse.data()), SmemLayoutLSEMma{});
  366. Tensor sdPsumMma = make_tensor(make_smem_ptr(shared_storage.tensors.mainloop.smem_dpsum.data()), SmemLayoutLSEMma{});
  367. bool const is_varlen_q = Varlen && params.cu_seqlens_q;
  368. bool const is_varlen_k = Varlen && params.cu_seqlens_k;
  369. int bidh_kv = params.qhead_per_khead_divmod.divide(bidh);
  370. Tensor mQ = make_tensor(make_gmem_ptr(params.ptr_Q), params.shape_Q, params.stride_Q)(_, _, bidh, !is_varlen_q ? bidb : 0);
  371. Tensor mdO = make_tensor(make_gmem_ptr(params.ptr_dO), params.shape_Q, params.stride_dO)(_, _, bidh, !is_varlen_q ? bidb : 0);
  372. Tensor mK = make_tensor(make_gmem_ptr(params.ptr_K), params.shape_K, params.stride_K)(_, _, bidh_kv, !is_varlen_k ? bidb : 0);
  373. Tensor mV = make_tensor(make_gmem_ptr(params.ptr_V), params.shape_K, params.stride_V)(_, _, bidh_kv, !is_varlen_k ? bidb : 0);
  374. Tensor mLSE = make_tensor(make_gmem_ptr(params.ptr_LSE_log2), params.shape_LSE, params.stride_LSE_log2)(_, bidh, !is_varlen_q ? bidb : 0);
  375. Tensor mdPsum = make_tensor(make_gmem_ptr(params.ptr_dPsum), params.shape_LSE, params.stride_dPsum)(_, bidh, !is_varlen_q ? bidb : 0);
  376. Tensor mdQaccum = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum*>(params.ptr_dQaccum)),
  377. params.shape_dQaccum, params.stride_dQaccum)(_, bidh, !is_varlen_q ? bidb : 0);
  378. Tensor gQ = local_tile(domain_offset(make_coord(seqlen_info.offset_q, _0{}), mQ), select<0, 2>(TileShape_MNK{}), make_coord(_, _0{})); // (M, K, _)
  379. Tensor gdO = local_tile(domain_offset(make_coord(seqlen_info.offset_q, _0{}), mdO), select<0, 2>(TileShape_MNK{}), make_coord(_, _0{})); // (M, K, _)
  380. Tensor gK = local_tile(domain_offset(make_coord(seqlen_info.offset_k, _0{}), mK), select<1, 2>(TileShape_MNK{}), make_coord(n_block, _0{})); // (N, K)
  381. Tensor gV = local_tile(domain_offset(make_coord(seqlen_info.offset_k, _0{}), mV), select<1, 2>(TileShape_MNK{}), make_coord(n_block, _0{})); // (N, K)
  382. Tensor gLSE = local_tile(domain_offset(make_coord(seqlen_info.offset_q_padded), mLSE), select<0>(TileShape_MNK{}), make_coord(_)); // (M, _)
  383. Tensor gdPsum = local_tile(domain_offset(make_coord(seqlen_info.offset_q_padded), mdPsum), select<0>(TileShape_MNK{}), make_coord(_)); // (M, _)
  384. Tensor gdQaccum = local_tile(domain_offset(make_coord(seqlen_info.offset_q_padded * kHeadDim), mdQaccum), Shape<Int<kBlockM * kHeadDim>>{}, make_coord(_)); // (M * K, _)
  385. GmemTiledCopyQKV gmem_tiled_copy_QKV;
  386. auto gmem_thr_copy_QKV = gmem_tiled_copy_QKV.get_thread_slice(thread_idx);
  387. auto gmem_thr0_copy_QKV = gmem_tiled_copy_QKV.get_thread_slice(_0{}); // For index calculation
  388. GmemTiledCopyLSE gmem_tiled_copy_lse;
  389. auto gmem_thr_copy_lse = gmem_tiled_copy_lse.get_thread_slice(thread_idx);
  390. R2STiledCopydQaccum r2s_tiled_copy_dQaccum;
  391. auto r2s_thr_copy_dQaccum = r2s_tiled_copy_dQaccum.get_thread_slice(thread_idx);
  392. Tensor tQgQ = gmem_thr_copy_QKV.partition_S(gQ);
  393. Tensor tQsQ = gmem_thr_copy_QKV.partition_D(sQ);
  394. Tensor tdOgdO = gmem_thr_copy_QKV.partition_S(gdO);
  395. Tensor tdOsdO = gmem_thr_copy_QKV.partition_D(sdO);
  396. Tensor tLSEgLSE = gmem_thr_copy_lse.partition_S(gLSE);
  397. Tensor tLSEsLSE = gmem_thr_copy_lse.partition_D(sLSE);
  398. Tensor tLSEgdPsum = gmem_thr_copy_lse.partition_S(gdPsum);
  399. Tensor tLSEsdPsum = gmem_thr_copy_lse.partition_D(sdPsum);
  400. // We can reuse r2s_thr_copy_dQaccum for this partitioning
  401. Tensor tdQgdQaccum = r2s_thr_copy_dQaccum.partition_D(gdQaccum);
  402. // if (blockIdx.x == 0 && threadIdx.x == 128) { print(mdQaccum); printf("\n"); print(gdQaccum_); printf("\n"); print(gdQaccum); printf("\n"); print(tdQgdQaccum); printf("\n"); }
  403. TiledMmaSdP tiled_mma_SdP;
  404. TiledMmadKV tiled_mma_dKV;
  405. TiledMmadQ tiled_mma_dQ;
  406. auto thr_mma_SdP = tiled_mma_SdP.get_thread_slice(thread_idx);
  407. auto thr_mma_dKV = tiled_mma_dKV.get_thread_slice(thread_idx);
  408. auto thr_mma_dQ = tiled_mma_dQ.get_thread_slice(thread_idx);
  409. // Allocate "fragments/descriptors"
  410. // We have to use the templated mma_partition_fragment_AB instead of cute::conditional_return or lambda,
  411. // because some partition_fragment_A/B don't compile.
  412. // https://stackoverflow.com/questions/50051473/if-constexpr-in-c17-does-not-work-in-a-non-templated-function
  413. Tensor tdPrV = mma_partition_fragment_AB</*A=*/SdP_swapAB>(thr_mma_SdP, sV);
  414. // Copy Atom retiling
  415. auto smem_copy_atom_SdP_B = cute::conditional_return<MmaSdPEvenN>(SmemCopyAtom{}, SmemCopyAtomHalf{});
  416. auto smem_tiled_copy_QdO = cute::conditional_return<!SdP_swapAB>(make_tiled_copy_A(SmemCopyAtom{}, tiled_mma_SdP), make_tiled_copy_B(smem_copy_atom_SdP_B, tiled_mma_SdP));
  417. auto smem_thr_copy_QdO = smem_tiled_copy_QdO.get_thread_slice(thread_idx);
  418. Tensor tSsQ = smem_thr_copy_QdO.partition_S(sQ);
  419. Tensor tdPsdO = smem_thr_copy_QdO.partition_S(sdO);
  420. auto smem_tiled_copy_KV = cute::conditional_return<!SdP_swapAB>(make_tiled_copy_B(smem_copy_atom_SdP_B, tiled_mma_SdP), make_tiled_copy_A(SmemCopyAtom{}, tiled_mma_SdP));
  421. auto smem_thr_copy_KV = smem_tiled_copy_KV.get_thread_slice(thread_idx);
  422. Tensor tSsK = smem_thr_copy_KV.partition_S(sK);
  423. Tensor tdPsV = smem_thr_copy_KV.partition_S(sV);
  424. auto r2s_tiled_copy_PdS = make_tiled_copy_C(R2SCopyAtomPdS{}, tiled_mma_SdP);
  425. auto r2s_thr_copy_PdS = r2s_tiled_copy_PdS.get_thread_slice(thread_idx);
  426. Tensor tPsP = r2s_thr_copy_PdS.partition_D(cute::conditional_return<!SdP_swapAB>(sP, sPt)); // ((Atom,AtomNum),PIPE_M,PIPE_N)
  427. Tensor tdSsdS = r2s_thr_copy_PdS.partition_D(cute::conditional_return<!SdP_swapAB>(sdS, sdSt)); // ((Atom,AtomNum),PIPE_M,PIPE_N)
  428. // if (blockIdx.x == 0 && threadIdx.x == 128) { print(r2s_thr_copy_PdS); print(sP); printf("\n"); print(sPt); printf("\n"); print(tPsP); printf("\n"); print(tdSsdS); printf("\n"); }
  429. auto smem_copy_atom_dKV_B = cute::conditional_return<MmadKVEvenN>(SmemCopyAtomTransposed{}, SmemCopyAtomTransposedHalf{});
  430. auto smem_tiled_copy_PdSt = cute::conditional_return<!dKV_swapAB>(make_tiled_copy_A(SmemCopyAtomTransposed{}, tiled_mma_dKV), make_tiled_copy_B(smem_copy_atom_dKV_B, tiled_mma_dKV));
  431. auto smem_thr_copy_PdSt = smem_tiled_copy_PdSt.get_thread_slice(thread_idx);
  432. Tensor tdVsPt = smem_thr_copy_PdSt.partition_S(sPt);
  433. Tensor tdKsdSt = smem_thr_copy_PdSt.partition_S(sdSt);
  434. auto smem_tiled_copy_QdOt = cute::conditional_return<!dKV_swapAB>(make_tiled_copy_B(smem_copy_atom_dKV_B, tiled_mma_dKV), make_tiled_copy_A(SmemCopyAtomTransposed{}, tiled_mma_dKV));
  435. auto smem_thr_copy_QdOt = smem_tiled_copy_QdOt.get_thread_slice(thread_idx);
  436. Tensor tdVsdOt = smem_thr_copy_QdOt.partition_S(sdOt);
  437. Tensor tdKsQt = smem_thr_copy_QdOt.partition_S(sQt);
  438. auto smem_tiled_copy_dS = cute::conditional_return<!dQ_swapAB>(
  439. make_tiled_copy_A(SmemCopyAtom{}, tiled_mma_dQ),
  440. make_tiled_copy_B(cute::conditional_return<MmadQEvenN>(SmemCopyAtom{}, SmemCopyAtomHalf{}), tiled_mma_dQ));
  441. auto smem_thr_copy_dS = smem_tiled_copy_dS.get_thread_slice(thread_idx);
  442. Tensor tdQsdS = smem_thr_copy_dS.partition_S(sdS);
  443. auto smem_tiled_copy_Kt = cute::conditional_return<!dQ_swapAB>(
  444. make_tiled_copy_B(cute::conditional_return<MmadQEvenN>(SmemCopyAtomTransposed{}, SmemCopyAtomTransposedHalf{}), tiled_mma_dQ),
  445. make_tiled_copy_A(SmemCopyAtomTransposed{}, tiled_mma_dQ));
  446. auto smem_thr_copy_Kt = smem_tiled_copy_Kt.get_thread_slice(thread_idx);
  447. Tensor tdQsKt = smem_thr_copy_Kt.partition_S(sKt);
  448. // thr_mma_SdP.partition_C(sLSEMma) has shape (MMA=4, MMA_M, MMA_N, PIPE), we only take the col indices
  449. // or row indices, depending on whether SdP_swapAB.
  450. Tensor tSsLSEMma = logical_divide(thr_mma_SdP.partition_C(sLSEMma), Shape<_2>{}); // (2, 2, MMA_M, MMA_N, PIPE)
  451. Tensor tSsLSE = group_modes<0, 2>(cute::conditional_return<!SdP_swapAB>(
  452. tSsLSEMma(make_coord(_0{}, _), _, _0{}, _), // (2, MMA_M, PIPE)
  453. tSsLSEMma(make_coord(_, _0{}), _0{}, _, _))); // (2, MMA_N, PIPE)
  454. Tensor tSsdPsumMma = logical_divide(thr_mma_SdP.partition_C(sdPsumMma), Shape<_2>{});
  455. Tensor tSsdPsum = group_modes<0, 2>(cute::conditional_return<!SdP_swapAB>(
  456. tSsdPsumMma(make_coord(_0{}, _), _, _0{}, _), // (2, MMA_M, PIPE)
  457. tSsdPsumMma(make_coord(_, _0{}), _0{}, _, _))); // (2, MMA_N, PIPE)
  458. // if (blockIdx.x == 0 && threadIdx.x == 128) { print(sLSEMma); printf("\n"); print(tLSEsLSE); printf("\n"); }
  459. // If we want to split the stats among the 8 threads that share the same rows.
  460. static constexpr int kStatsPerThread = cute::ceil_div(decltype(size(tSsLSE))::value, 8);
  461. // Predicates
  462. Tensor cQ = cute::make_identity_tensor(select<0, 2>(TileShape_MNK{}));
  463. Tensor tQcQ = gmem_thr_copy_QKV.partition_S(cQ);
  464. Tensor t0QcQ = gmem_thr0_copy_QKV.partition_S(cQ);
  465. Tensor tQpQ = make_tensor<bool>(make_shape(size<2>(tQsQ)));
  466. #pragma unroll
  467. for (int k = 0; k < size(tQpQ); ++k) { tQpQ(k) = get<1>(tQcQ(_0{}, _0{}, k)) < get<1>(params.shape_Q); }
  468. Tensor cLSE = cute::make_identity_tensor(select<0>(TileShape_MNK{}));
  469. Tensor tLSEcLSE = gmem_thr_copy_lse.partition_S(cLSE);
  470. int const seqlen_q = seqlen_info.seqlen_q;
  471. int const seqlen_k = seqlen_info.seqlen_k;
  472. flash::Mask<kBlockM, kBlockN, false /*PackGQA*/, TiledMmaSdP, SdP_swapAB> mask(
  473. thread_idx, seqlen_q, seqlen_k, params.window_size_left, params.window_size_right, 0 /*sink_token_length*/,
  474. params.qhead_per_khead_divmod
  475. );
  476. {
  477. Tensor tKgK = gmem_thr_copy_QKV.partition_S(gK); // (KCPY, KCPY_N, KCPY_K, nblocksN)
  478. Tensor tKsK = gmem_thr_copy_QKV.partition_D(sK);
  479. Tensor tVgV = gmem_thr_copy_QKV.partition_S(gV); // (VCPY, VCPY_N, VCPY_K, nblocksN)
  480. Tensor tVsV = gmem_thr_copy_QKV.partition_D(sV);
  481. // Predicates
  482. Tensor cKV = cute::make_identity_tensor(select<1, 2>(TileShape_MNK{}));
  483. Tensor tKVcKV = gmem_thr_copy_QKV.partition_S(cKV);
  484. Tensor t0KVcKV = gmem_thr0_copy_QKV.partition_S(cKV);
  485. Tensor tKVpKV = make_tensor<bool>(make_shape(size<2>(tKsK)));
  486. #pragma unroll
  487. for (int k = 0; k < size(tKVpKV); ++k) { tKVpKV(k) = get<1>(tKVcKV(_0{}, _0{}, k)) < get<1>(params.shape_K); }
  488. // Do we need bound check to make sure the row doesn't go above kBlockN
  489. static constexpr bool EvenN = kBlockN % CUTE_STATIC_V(shape<0>(GmemLayoutAtom{})) == 0;
  490. // static_assert(EvenN); // It simplifies the loading of K and V
  491. // Instead of passing in tKVcKV, we pass in t0KVcKV and subtract the offset from the limit
  492. // (seqlen_k - n_block * kBlockN). This is because the entries of t0KVcKV are known at compile time.
  493. // int const seqlenk_row_limit = -int(get<0>(tKVcKV(_0{}, _0{}, _0{}))) + (EvenN
  494. // ? seqlen_info.seqlen_k - n_block * kBlockN
  495. // : std::min(seqlen_info.seqlen_k - n_block * kBlockN, kBlockN));
  496. // // Need Clear_OOB_MN to be true here since the gemm will sum over the kBlockN dimension
  497. // flash::copy</*Is_even_MN=*/false, /*Is_even_K=*/false, /*Clear_OOB_MN=*/true, /*Clear_OOB_K=*/true>(
  498. // gmem_tiled_copy_QKV, tVgV, tVsV, t0KVcKV, tKVpKV, seqlenk_row_limit);
  499. int const seqlenk_row_limit = seqlen_k - n_block * kBlockN - get<0>(tKVcKV(_0{}, _0{}, _0{}));
  500. #pragma unroll
  501. for (int m = 0; m < size<1>(tVsV); ++m) {
  502. // If kBlockN doesn't evenly divide the tiled copy, only the last `m` needs to be checked
  503. if (EvenN || m < size<1>(tVsV) - 1 || get<0>(tKVcKV(_0{}, m, _0{})) < kBlockN) {
  504. bool const predicate_n = get<0>(t0KVcKV(_0{}, m, _0{})) < seqlenk_row_limit;
  505. #pragma unroll
  506. for (int k = 0; k < size<2>(tVsV); ++k) {
  507. cute::copy(gmem_tiled_copy_QKV.with(tKVpKV(k) && predicate_n), tVgV(_, m, k), tVsV(_, m, k));
  508. }
  509. }
  510. }
  511. if constexpr (V_in_regs) { flash::cp_async_fence(); }
  512. // flash::copy</*Is_even_MN=*/false, /*Is_even_K=*/false, /*Clear_OOB_MN=*/true, /*Clear_OOB_K=*/true>(
  513. // gmem_tiled_copy_QKV, tKgK, tKsK, t0KVcKV, tKVpKV, seqlenk_row_limit);
  514. #pragma unroll
  515. for (int m = 0; m < size<1>(tKsK); ++m) {
  516. if (EvenN || m < size<1>(tKsK) - 1 || get<0>(tKVcKV(_0{}, m, _0{})) < kBlockN) {
  517. bool const predicate_n = get<0>(t0KVcKV(_0{}, m, _0{})) < seqlenk_row_limit;
  518. #pragma unroll
  519. for (int k = 0; k < size<2>(tKsK); ++k) {
  520. cute::copy(gmem_tiled_copy_QKV.with(tKVpKV(k) && predicate_n), tKgK(_, m, k), tKsK(_, m, k));
  521. }
  522. }
  523. }
  524. flash::cp_async_fence();
  525. }
  526. if constexpr (V_in_regs) {
  527. flash::cp_async_wait<1>();
  528. __syncthreads();
  529. Tensor tdPrV_copy_view = smem_thr_copy_KV.retile_D(tdPrV);
  530. Tensor tdPsV_copy_view = smem_thr_copy_KV.partition_S(sV);
  531. cute::copy(smem_tiled_copy_KV, tdPsV_copy_view, tdPrV_copy_view);
  532. __syncthreads(); // Sync to avoid loading Q to smem_q, which overlaps with smem_v
  533. }
  534. // Do we need bound check to make sure the row doesn't go above kBlockM
  535. static constexpr int kBlockM = get<0>(TileShape_MNK{});
  536. static constexpr bool EvenM = kBlockM % CUTE_STATIC_V(shape<0>(GmemLayoutAtom{})) == 0;
  537. auto load_Q_LSE = [&] (int const m_block, int const smem_pipe_write) {
  538. // if (cute::thread0()) { printf("Inside load_Q_LSE, m_block = %d, smem_pipe_write = %d\n", m_block, smem_pipe_write); }
  539. Tensor tQsQ_cur = tQsQ(_, _, _, smem_pipe_write);
  540. Tensor tQgQ_cur = tQgQ(_, _, _, m_block);
  541. // Instead of passing in tQcQ, we pass in t0QcQ and subtract the offset from the limit
  542. // (seqlen_q - m_block * kBlockM). This is because the entries of t0QcQ are known at compile time.
  543. // int const seqlenq_row_limit = -int(get<0>(tQcQ(_0{}, _0{}, _0{}))) + (EvenM
  544. // ? seqlen_info.seqlen_q - m_block * kBlockM
  545. // : std::min(seqlen_info.seqlen_q - m_block * kBlockM, kBlockM));
  546. // Need Clear_OOB_MN to be true here since the gemm will sum over the kBlockM dimension
  547. // flash::copy</*Is_even_MN=*/false, /*Is_even_K=*/false, /*Clear_OOB_MN=*/true, /*Clear_OOB_K=*/true>(
  548. // gmem_tiled_copy_QKV, tQgQ(_, _, _, m_block), tQsQ_cur, t0QcQ, tQpQ, seqlenq_row_limit);
  549. int const seqlenq_row_limit = seqlen_info.seqlen_q - m_block * kBlockM - get<0>(tQcQ(_0{}, _0{}, _0{}));
  550. #pragma unroll
  551. for (int m = 0; m < size<1>(tQsQ); ++m) {
  552. // If kBlockM doesn't evenly divide the tiled copy, only the last `m` needs to be checked
  553. if (EvenM || m < size<1>(tQsQ) - 1 || get<0>(tQcQ(_0{}, m, _0{})) < kBlockM) {
  554. bool const predicate_m = get<0>(t0QcQ(_0{}, m, _0{})) < seqlenq_row_limit;
  555. #pragma unroll
  556. for (int k = 0; k < size<2>(tQsQ); ++k) {
  557. cute::copy(gmem_tiled_copy_QKV.with(tQpQ(k) && predicate_m), tQgQ_cur(_, m, k), tQsQ_cur(_, m, k));
  558. }
  559. }
  560. }
  561. Tensor tLSEgLSE_cur = tLSEgLSE(_, _, m_block);
  562. Tensor tLSEsLSE_cur = tLSEsLSE(_, _, smem_pipe_write);
  563. // We made sure LSE length is padded so we read `kBlockM` elements so that all
  564. // elements in sLSE are filled. Without this we might have uninitialized sLSE values.
  565. #pragma unroll
  566. for (int m = 0; m < size<1>(tLSEsLSE); ++m) {
  567. if (get<0>(tLSEcLSE(_0{}, m)) < kBlockM) {
  568. cute::copy(gmem_tiled_copy_lse, tLSEgLSE_cur(_, m), tLSEsLSE_cur(_, m));
  569. }
  570. }
  571. };
  572. auto load_dO_dPsum = [&] (int const m_block, int const smem_pipe_write) {
  573. // if (cute::thread0()) { printf("Inside load_dO_dPsum, m_block = %d, smem_pipe_write = %d\n", m_block, smem_pipe_write); }
  574. Tensor tdOsdO_cur = tdOsdO(_, _, _, smem_pipe_write);
  575. Tensor tdOgdO_cur = tdOgdO(_, _, _, m_block);
  576. // int const seqlenq_row_limit = -int(get<0>(tQcQ(_0{}, _0{}, _0{}))) + (EvenM
  577. // ? seqlen_info.seqlen_q - m_block * kBlockM
  578. // : std::min(seqlen_info.seqlen_q - m_block * kBlockM, kBlockM));
  579. // flash::copy</*Is_even_MN=*/false, /*Is_even_K=*/false, /*Clear_OOB_MN=*/true, /*Clear_OOB_K=*/true>(
  580. // gmem_tiled_copy_QKV, tdOgdO(_, _, _, m_block), tdOsdO_cur, t0QcQ, tQpQ, seqlenq_row_limit);
  581. int const seqlenq_row_limit = seqlen_info.seqlen_q - m_block * kBlockM - get<0>(tQcQ(_0{}, _0{}, _0{}));
  582. #pragma unroll
  583. for (int m = 0; m < size<1>(tdOsdO); ++m) {
  584. // If kBlockM doesn't evenly divide the tiled copy, only the last `m` needs to be checked
  585. if (EvenM || m < size<1>(tdOsdO) - 1 || get<0>(tQcQ(_0{}, m, _0{})) < kBlockM) {
  586. bool const predicate_m = get<0>(t0QcQ(_0{}, m, _0{})) < seqlenq_row_limit;
  587. #pragma unroll
  588. for (int k = 0; k < size<2>(tdOsdO); ++k) {
  589. cute::copy(gmem_tiled_copy_QKV.with(tQpQ(k) && predicate_m), tdOgdO_cur(_, m, k), tdOsdO_cur(_, m, k));
  590. }
  591. }
  592. }
  593. Tensor tLSEgdPsum_cur = tLSEgdPsum(_, _, m_block);
  594. Tensor tLSEsdPsum_cur = tLSEsdPsum(_, _, smem_pipe_write);
  595. #pragma unroll
  596. for (int m = 0; m < size<1>(tLSEsdPsum); ++m) {
  597. if (get<0>(tLSEcLSE(_0{}, m)) < kBlockM) {
  598. cute::copy(gmem_tiled_copy_lse, tLSEgdPsum_cur(_, m), tLSEsdPsum_cur(_, m));
  599. }
  600. }
  601. };
  602. int m_block = m_block_min;
  603. // Note, using the for_each() function here to ensure `stage` is of type Int<x>.
  604. for_each(make_int_sequence<kStages>{}, [&] (auto stage) {
  605. static constexpr bool Is_first_stage = CUTE_STATIC_V(stage) == 0;
  606. static constexpr bool Is_last_stage = CUTE_STATIC_V(stage) == kStages - 1;
  607. if constexpr (!Is_last_stage || kStages == 1) {
  608. if (Is_first_stage || m_block + stage < m_block_max) {
  609. load_Q_LSE(m_block + stage, stage);
  610. }
  611. }
  612. // We want the fence outside the if statement to have a fixed number of cp.async commits.
  613. // so that we can wait with the correct number of outstanding commits.
  614. cute::cp_async_fence();
  615. if constexpr (stage < kStages_dO) {
  616. if (Is_first_stage || m_block + stage < m_block_max) {
  617. load_dO_dPsum(m_block + stage, stage);
  618. }
  619. cute::cp_async_fence();
  620. }
  621. });
  622. int smem_pipe_read = 0, smem_pipe_read_do = 0, smem_pipe_write = kStages - 1, smem_pipe_write_do = 0;
  623. auto load_Q_next = [&] {
  624. // if (cute::thread0()) { printf("m_block = %d, m_block_max = %d, smem_pipe_write = %d\n", m_block, m_block_max, smem_pipe_write); }
  625. if (m_block + (kStages > 1 ? kStages - 1 : 1) < m_block_max) {
  626. load_Q_LSE(m_block + (kStages > 1 ? kStages - 1 : 1), kStages > 1 ? smem_pipe_write : 0);
  627. }
  628. cute::cp_async_fence();
  629. };
  630. auto load_dO_next = [&] {
  631. // int smem_pipe_write_do_cur = Q_dO_same_stages ? smem_pipe_write : smem_pipe_write_do;
  632. if (m_block + kStages_dO < m_block_max) {
  633. // load_dO_dPsum(m_block + kStages_dO, kStages_dO > 1 ? smem_pipe_write_do_cur : 0);
  634. load_dO_dPsum(m_block + kStages_dO, kStages_dO > 1 ? smem_pipe_write_do : 0);
  635. }
  636. cute::cp_async_fence();
  637. };
  638. clear(tdKrdK);
  639. clear(tdVrdV);
  640. auto bwd_step = [&](int m_block, auto mask_fn) {
  641. Tensor tSrS = partition_fragment_C(tiled_mma_SdP, select<!SdP_swapAB ? 0 : 1, !SdP_swapAB ? 1 : 0>(TileShape_MNK{}));
  642. clear(tSrS);
  643. flash::cp_async_wait<(kStages > 1) ? 1 : 0>();
  644. __syncthreads();
  645. Tensor tSrQ = mma_partition_fragment_AB</*A=*/!SdP_swapAB>(thr_mma_SdP, sQ(_, _, _0{}));
  646. Tensor tSrK = mma_partition_fragment_AB</*A=*/SdP_swapAB>(thr_mma_SdP, sK);
  647. // if (cute::thread0()) { print(tiled_mma_SdP); print(tSrS); printf("\n"); print(tSrQ); printf("\n"); print(tSrK); printf("\n"); print(tSsQ); printf("\n"); print(tSsK); printf("\n"); }
  648. flash::gemm_sm80<false /*A_in_regs*/, false /*B_in_regs*/, SdP_swapAB>(
  649. tSrS, tSrQ, tSrK, tSsQ(_, _, _, kStages > 1 ? smem_pipe_read : 0), tSsK,
  650. tiled_mma_SdP, smem_tiled_copy_QdO, smem_tiled_copy_KV, smem_thr_copy_QdO, smem_thr_copy_KV, nullptr /*hook*/);
  651. Tensor tLSErLSE = cute::conditional_return<!ShuffleLSE>(make_fragment_like(tSsLSE(_, _0{})), make_tensor<ElementAccum>(Int<kStatsPerThread>{}));
  652. if constexpr (!ShuffleLSE) {
  653. cute::copy(tSsLSE(_, kStages > 1 ? smem_pipe_read : 0), tLSErLSE);
  654. } else {
  655. #pragma unroll
  656. for (int i = 0; i < kStatsPerThread; ++i) {
  657. // It's ok to read OOB, since we made sure sLSE is large enough and we won't use the OOB values
  658. tLSErLSE(i) = tSsLSE((thread_idx % 32) / 4 + i * 8, kStages > 1 ? smem_pipe_read : 0);
  659. }
  660. }
  661. if constexpr (Has_softcap) { flash::apply_softcap(tSrS, params.softcap_val); }
  662. // Reshape tSrS from (4, MMA_N, MMA_M) to (nrow=(2, MMA_M), ncol=(2, MMA_N))
  663. Tensor scores = make_tensor(tSrS.data(), flash::convert_layout_acc_rowcol</*Transposed=*/SdP_swapAB>(tSrS.layout()));
  664. // dtanh needs to happen before masking, otherwise we get 1 - (-inf)^2 = NaN in the dtanh
  665. // if (cute::thread0()) { print_tensor(scores); }
  666. auto dtanh = [&] { if constexpr (Has_softcap) return flash::calculate_dtanh(scores); else return nullptr; }();
  667. mask_fn(tSrS, m_block);
  668. #pragma unroll
  669. for (int mi = 0; mi < size<0>(scores); ++mi) {
  670. float const lse_scaled = [&] {
  671. if constexpr (!ShuffleLSE) return tLSErLSE(mi);
  672. else return __shfl_sync(0xffffffff, tLSErLSE(mi / 8), (mi % 8) * 4 + (thread_idx % 4));
  673. }();
  674. #pragma unroll
  675. for (int ni = 0; ni < size<1>(scores); ++ni) {
  676. scores(mi, ni) = exp2f(scores(mi, ni) * params.softmax_scale_log2 - lse_scaled);
  677. }
  678. }
  679. Tensor tdPrdP = partition_fragment_C(tiled_mma_SdP, select<!SdP_swapAB ? 0 : 1, !SdP_swapAB ? 1 : 0>(TileShape_MNK{}));
  680. clear(tdPrdP);
  681. int smem_pipe_read_do_cur = Q_dO_same_stages ? smem_pipe_read : smem_pipe_read_do;
  682. flash::cp_async_wait<(kStages_dO > 1) ? 1 : 0>();
  683. __syncthreads();
  684. auto hook = cute::conditional_return<(kStages > 1)>(load_Q_next, nullptr);
  685. Tensor tdPrdO = mma_partition_fragment_AB</*A=*/!SdP_swapAB>(thr_mma_SdP, sdO(_, _, _0{}));
  686. Tensor tdPrV_cur = cute::conditional_return<V_in_regs>(tdPrV, mma_partition_fragment_AB</*A=*/SdP_swapAB>(thr_mma_SdP, sV));
  687. flash::gemm_sm80<false /*A_in_regs*/, V_in_regs, SdP_swapAB>(
  688. tdPrdP, tdPrdO, tdPrV_cur, tdPsdO(_, _, _, kStages_dO > 1 ? smem_pipe_read_do_cur : 0), tdPsV,
  689. tiled_mma_SdP, smem_tiled_copy_QdO, smem_tiled_copy_KV, smem_thr_copy_QdO, smem_thr_copy_KV, hook);
  690. Tensor tLSErdPsum = cute::conditional_return<!ShuffledPsum>(make_fragment_like(tSsdPsum(_, _0{})), make_tensor<ElementAccum>(Int<kStatsPerThread>{}));
  691. if constexpr (!ShuffledPsum) {
  692. cute::copy(tSsdPsum(_, kStages_dO > 1 ? smem_pipe_read_do_cur : 0), tLSErdPsum);
  693. } else {
  694. #pragma unroll
  695. for (int i = 0; i < kStatsPerThread; ++i) {
  696. tLSErdPsum(i) = tSsdPsum((thread_idx % 32) / 4 + i * 8, kStages_dO > 1 ? smem_pipe_read_do_cur : 0);
  697. }
  698. }
  699. // Reshape tdPrdP from (4, MMA_N, MMA_M) to (nrow=(2, MMA_M), ncol=(2, MMA_N))
  700. Tensor dS = make_tensor(tdPrdP.data(), scores.layout());
  701. #pragma unroll
  702. for (int mi = 0; mi < size<0>(dS); ++mi) {
  703. float const dP_sum_cur = [&] {
  704. if constexpr (!ShuffledPsum) return tLSErdPsum(mi);
  705. else return __shfl_sync(0xffffffff, tLSErdPsum(mi / 8), (mi % 8) * 4 + (thread_idx % 4));
  706. }();
  707. #pragma unroll
  708. for (int ni = 0; ni < size<1>(dS); ++ni) {
  709. dS(mi, ni) = scores(mi, ni) * (dS(mi, ni) - dP_sum_cur);
  710. if constexpr (Has_softcap) { dS(mi, ni) *= dtanh(mi, ni); }
  711. }
  712. }
  713. // if (cute::thread0()) { print_tensor(dS); }
  714. // Convert scores from fp32 to fp16/bf16
  715. Tensor rP = make_tensor_like<Element>(tSrS);
  716. flash::convert_type_out(tSrS, rP);
  717. if constexpr (!Mma_dKV_is_RS) {
  718. Tensor tPaP = r2s_thr_copy_PdS.retile_S(rP); // ((Atom,AtomNum), MMA_N, MMA_N)
  719. cute::copy(r2s_tiled_copy_PdS, tPaP, tPsP);
  720. }
  721. Tensor rdS = make_tensor_like<Element>(tdPrdP);
  722. flash::convert_type_out(tdPrdP, rdS);
  723. if constexpr (!Mma_dKV_is_RS) { __syncthreads(); } // Make sure P is written
  724. // For hdim 64, It's faster to write to smem_dS first before the dV gemm
  725. Tensor tdSadS = r2s_thr_copy_PdS.retile_S(rdS); // ((Atom,AtomNum), MMA_N, MMA_N)
  726. cute::copy(r2s_tiled_copy_PdS, tdSadS, tdSsdS);
  727. Tensor tdVrdO = mma_partition_fragment_AB</*A=*/dKV_swapAB>(thr_mma_dKV, sdOt(_, _, _0{}));
  728. Tensor tdVsdO_cur = tdVsdOt(_, _, _, kStages_dO > 1 ? smem_pipe_read_do_cur : 0);
  729. if constexpr (Mma_dKV_is_RS) {
  730. Tensor tdVrP = make_tensor(rP.data(), convert_layout_acc_Aregs<TiledMmadKV>(tSrS.layout()));
  731. flash::gemm_rs_sm80(tdVrdV, tdVrP, tdVrdO, tdVsdO_cur, tiled_mma_dKV, smem_tiled_copy_QdOt, smem_thr_copy_QdOt);
  732. } else {
  733. Tensor tdVrP = mma_partition_fragment_AB</*A=*/!dKV_swapAB>(thr_mma_dKV, sPt);
  734. flash::gemm_sm80<false /*A_in_regs*/, false /*B_in_regs*/, /*SwapAB=*/dKV_swapAB>(
  735. tdVrdV, tdVrP, tdVrdO, tdVsPt, tdVsdO_cur,
  736. tiled_mma_dKV, smem_tiled_copy_PdSt, smem_tiled_copy_QdOt, smem_thr_copy_PdSt, smem_thr_copy_QdOt, nullptr);
  737. }
  738. // if (cute::thread0()) { print_tensor(tdVrdV); }
  739. __syncthreads(); // make sure sdS is written
  740. auto do_mma_dQ = [&] (auto hook) {
  741. Tensor tdQrdQ = partition_fragment_C(tiled_mma_dQ, select<!dQ_swapAB ? 0 : 2, !dQ_swapAB ? 2 : 0>(TileShape_MNK{}));
  742. clear(tdQrdQ);
  743. Tensor tdQrdS = mma_partition_fragment_AB</*A=*/!dQ_swapAB>(thr_mma_dQ, sdS);
  744. Tensor tdQrK = mma_partition_fragment_AB</*A=*/dQ_swapAB>(thr_mma_dQ, sKt);
  745. flash::gemm_sm80<false /*A_in_regs*/, false /*B_in_regs*/, /*SwapAB=*/dQ_swapAB>(
  746. tdQrdQ, tdQrdS, tdQrK, tdQsdS, tdQsKt, tiled_mma_dQ,
  747. // smem_tiled_copy_dS, smem_tiled_copy_Kt, smem_thr_copy_dS, smem_thr_copy_Kt, load_dO_next);
  748. smem_tiled_copy_dS, smem_tiled_copy_Kt, smem_thr_copy_dS, smem_thr_copy_Kt, hook);
  749. // if (cute::thread0()) { print_tensor(tdQrdQ); }
  750. // We can reuse r2s_thr_copy_dQaccum for this partitioning
  751. Tensor tdQrdQ_atomic = r2s_thr_copy_dQaccum.retile_S(tdQrdQ);
  752. Tensor tdQgdQaccum_atomic = tdQgdQaccum(_, _, m_block);
  753. static_assert(CUTE_STATIC_V(size(tdQrdQ_atomic)) == CUTE_STATIC_V(size(tdQgdQaccum_atomic)));
  754. #pragma unroll
  755. for (int i = 0; i < size(tdQrdQ_atomic); ++i) { atomicAdd(&tdQgdQaccum_atomic(i), tdQrdQ_atomic(i)); }
  756. };
  757. // If kStages == 1, we want to do Mma_dK first so we can start loading Q for the next iteration
  758. if constexpr (kStages > 1) { do_mma_dQ(load_dO_next); }
  759. Tensor tdKrQ = mma_partition_fragment_AB</*A=*/dKV_swapAB>(thr_mma_dKV, sQt(_, _, _0{}));
  760. Tensor tdKsQ_cur = tdKsQt(_, _, _, kStages > 1 ? smem_pipe_read : 0);
  761. if constexpr (Mma_dKV_is_RS) {
  762. Tensor tdKrdS = make_tensor(rdS.data(), convert_layout_acc_Aregs<TiledMmadKV>(tdPrdP.layout()));
  763. flash::gemm_rs_sm80(tdKrdK, tdKrdS, tdKrQ, tdKsQ_cur, tiled_mma_dKV, smem_tiled_copy_QdOt, smem_thr_copy_QdOt);
  764. } else {
  765. Tensor tdKrdS = mma_partition_fragment_AB</*A=*/!dKV_swapAB>(thr_mma_dKV, sdSt);
  766. flash::gemm_sm80<false /*A_in_regs*/, false /*B_in_regs*/, /*SwapAB=*/dKV_swapAB>(
  767. tdKrdK, tdKrdS, tdKrQ, tdKsdSt, tdKsQ_cur,
  768. tiled_mma_dKV, smem_tiled_copy_PdSt, smem_tiled_copy_QdOt, smem_thr_copy_PdSt, smem_thr_copy_QdOt, cute::conditional_return<(kStages > 1)>(nullptr, load_dO_next));
  769. }
  770. if constexpr (kStages == 1) {
  771. __syncthreads();
  772. do_mma_dQ(load_Q_next);
  773. }
  774. // if (cute::thread0()) { print_tensor(tdKrdK); }
  775. smem_pipe_read = smem_pipe_read < kStages - 1 ? smem_pipe_read + 1 : 0;
  776. smem_pipe_read_do = smem_pipe_read_do < kStages_dO - 1 ? smem_pipe_read_do + 1 : 0;
  777. smem_pipe_write = smem_pipe_write < kStages - 1 ? smem_pipe_write + 1 : 0;
  778. smem_pipe_write_do = smem_pipe_write_do < kStages_dO - 1 ? smem_pipe_write_do + 1 : 0;
  779. };
  780. // We have separate iterations with causal masking. Not necessary for hdim 128 but for hdim 64
  781. // this helps quite a bit to not have to do causal masking for most of the iterations.
  782. if constexpr ((Is_causal || Is_local) && SeparateMaskingIterations) {
  783. auto mask_fn = [&](auto& tSrS, int m_block) { mask.template apply<true /*Seqlenk_mask*/, Is_causal, Is_local>(tSrS, m_block, n_block); };
  784. int const m_block_masking_max = ((n_block + 1) * kBlockN - 1 + seqlen_q - seqlen_k - params.window_size_right) / kBlockM + 1;
  785. CUTLASS_PRAGMA_NO_UNROLL
  786. for (; m_block < std::min(m_block_max, m_block_masking_max); ++m_block) {
  787. bwd_step(m_block, mask_fn);
  788. }
  789. }
  790. static constexpr int kBlockN = get<1>(TileShape_MNK{});
  791. int const m_block_max_before_local_mask = !Is_local || !SeparateMaskingIterations
  792. ? m_block_max
  793. : std::min(m_block_max, (n_block * kBlockN + seqlen_q - seqlen_k + params.window_size_left) / kBlockM);
  794. auto mask_fn = [&](auto& tSrS, int m_block) { mask.template apply<true /*Seqlenk_mask*/, Is_causal && !SeparateMaskingIterations, Is_local && !SeparateMaskingIterations>(tSrS, m_block, n_block); };
  795. CUTLASS_PRAGMA_NO_UNROLL
  796. for (; m_block < m_block_max_before_local_mask; ++m_block) {
  797. bwd_step(m_block, mask_fn);
  798. }
  799. if constexpr (Is_local && SeparateMaskingIterations) {
  800. auto mask_fn = [&](auto& tSrS, int m_block) { mask.template apply<true /*Seqlenk_mask*/, false /*Causal_mask*/, Is_local>(tSrS, m_block, n_block); };
  801. CUTLASS_PRAGMA_NO_UNROLL
  802. for (; m_block < m_block_max; ++m_block) {
  803. bwd_step(m_block, mask_fn);
  804. }
  805. }
  806. // if (blockIdx.x == 0 && threadIdx.x == 128) { print_tensor(tdVrdV); }
  807. #pragma unroll
  808. for (int i = 0; i < size(tdKrdK); ++i) { tdKrdK(i) *= params.softmax_scale; }
  809. return true;
  810. }
  811. };
  812. } // namespace flash