mainloop_fwd_sm90_tma_gmma_ws.hpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. /******************************************************************************
  2. * Copyright (c) 2024, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, 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 "cutlass/pipeline/pipeline.hpp"
  10. #include "cute/tensor.hpp"
  11. #include "cutlass/gemm/collective/collective_builder.hpp"
  12. #include "named_barrier.hpp"
  13. #include "utils.h"
  14. namespace flash {
  15. using namespace cute;
  16. // 4 warps
  17. struct SmemTransposeFp8_64x64 {
  18. using Element = cutlass::float_e4m3_t;
  19. using ldsm_thread_shape = Shape<_4, _1, _8, _4>;
  20. using ldsm_value_shape = Shape<_2, _8, _2, _1>;
  21. using ldsm_value_stride = Stride<_2, _4, _1, _0>;
  22. using TiledCopyLDSM = decltype(make_tiled_copy(
  23. Copy_Atom<SM75_U16x8_LDSM_T, Element>{}, Layout<ldsm_thread_shape>{},
  24. Layout<ldsm_value_shape, ldsm_value_stride>{}));
  25. TiledCopyLDSM tiled_copy_ldsm;
  26. using stsm_thread_shape = Shape<_4, _1, _8, _4>;
  27. // using stsm_thread_stride = Stride<_1, _0, _4, _32>;
  28. #ifndef NO_FP8_COLUMN_PERMUTE
  29. using stsm_value_shape = Shape<_4, _4, _1, _2>;
  30. using stsm_value_stride = Stride<_1, _8, _0, _4>;
  31. #else
  32. using stsm_value_shape = Shape<_4, _4, _2, _1>;
  33. using stsm_value_stride = Stride<_1, _8, _4, _0>;
  34. #endif
  35. using TiledCopySTSM =
  36. decltype(make_tiled_copy(Copy_Atom<SM90_U32x4_STSM_N, Element>{},
  37. Layout<stsm_thread_shape>{},
  38. Layout<stsm_value_shape, stsm_value_stride>{}));
  39. TiledCopySTSM tiled_copy_stsm;
  40. template <class SmemTensor, class SmemTensorOut>
  41. CUTLASS_DEVICE void operator()(SmemTensor &&s_in, SmemTensorOut &&s_out) {
  42. using namespace cute;
  43. auto tid = threadIdx.x;
  44. auto thr_copy_ldsm = tiled_copy_ldsm.get_thread_slice(tid);
  45. auto thr_copy_stsm = tiled_copy_stsm.get_thread_slice(tid);
  46. auto tXsX = thr_copy_ldsm.partition_S(s_in);
  47. auto tXrX = make_tensor<Element>(shape(tXsX));
  48. auto tXsX_out = thr_copy_stsm.partition_D(s_out);
  49. cute::copy(tiled_copy_ldsm, tXsX, tXrX);
  50. auto data = tXrX.data();
  51. // size(tXrX) == 32
  52. CUTLASS_PRAGMA_UNROLL
  53. for (int n = 0; n < size(tXrX); n += 8) {
  54. uint32_t *data_32bit = reinterpret_cast<uint32_t *>(&data[n]);
  55. auto upper = data_32bit[0];
  56. auto lower = data_32bit[1];
  57. data_32bit[0] = __byte_perm(upper, lower, 0x6420);
  58. data_32bit[1] = __byte_perm(upper, lower, 0x7531);
  59. }
  60. cute::copy(tiled_copy_stsm, tXrX, tXsX_out);
  61. }
  62. };
  63. template <typename Ktraits, bool Is_causal, bool Is_local, typename Seqlen_traits, typename Seqlen_traits_Q = Seqlen_traits>
  64. struct CollectiveMainloopFwd {
  65. using Element = typename Ktraits::Element;
  66. using TileShape_MNK = typename Ktraits::TileShape_MNK;
  67. using ClusterShape = typename Ktraits::ClusterShape_MNK;
  68. static constexpr int kStages = Ktraits::kStages;
  69. static constexpr int kHeadDim = Ktraits::kHeadDim;
  70. // static constexpr int kBlockM = Ktraits::kBlockM;
  71. // static constexpr int kBlockN = Ktraits::kBlockN;
  72. // static constexpr int kBlockH = Ktraits::kBlockH;
  73. static constexpr bool Is_split = Ktraits::Is_split;
  74. static constexpr bool No_smem_O = Ktraits::No_smem_O;
  75. using GmemTiledCopyQ = cute::SM90_TMA_LOAD;
  76. using GmemTiledCopyKV = decltype(cutlass::gemm::collective::detail::sm90_cluster_shape_to_tma_atom(shape<0>(ClusterShape{})));
  77. using SmemLayoutQ = typename Ktraits::SmemLayoutQ;
  78. using SmemLayoutQCopy = typename Ktraits::SmemLayoutQCopy;
  79. using TileShapeQCopy = typename Ktraits::TileShapeQCopy;
  80. using SmemLayoutK = typename Ktraits::SmemLayoutK;
  81. using SmemLayoutV = typename Ktraits::SmemLayoutV;
  82. using SmemLayoutVt = typename Ktraits::SmemLayoutVt;
  83. using TMA_Q = decltype(make_tma_copy(
  84. GmemTiledCopyQ{},
  85. make_tensor(
  86. make_gmem_ptr(static_cast<Element const*>(nullptr)),
  87. repeat_like(typename Seqlen_traits_Q::StrideT{}, int32_t(0)),
  88. typename Seqlen_traits_Q::StrideT{}
  89. ),
  90. SmemLayoutQCopy{},
  91. TileShapeQCopy{},
  92. _1{})); // no mcast for Q
  93. using TMA_K = decltype(make_tma_copy(
  94. GmemTiledCopyKV{},
  95. make_tensor(
  96. make_gmem_ptr(static_cast<Element const*>(nullptr)),
  97. repeat_like(typename Seqlen_traits::StrideT{}, int32_t(0)),
  98. typename Seqlen_traits::StrideT{}
  99. ),
  100. take<0, 2>(SmemLayoutK{}),
  101. select<1, 2>(TileShape_MNK{}),
  102. size<0>(ClusterShape{}))); // mcast along M mode for this N load, if any
  103. // TMA_V may differ from TMA_K for fp8 kernel (e.g. swizzling mode)
  104. using TMA_V = decltype(make_tma_copy(
  105. GmemTiledCopyKV{},
  106. make_tensor(
  107. make_gmem_ptr(static_cast<Element const*>(nullptr)),
  108. repeat_like(typename Seqlen_traits::StrideT{}, int32_t(0)),
  109. typename Seqlen_traits::StrideT{}
  110. ),
  111. take<0, 2>(SmemLayoutV{}),
  112. select<1, 2>(TileShape_MNK{}),
  113. size<0>(ClusterShape{}))); // mcast along M mode for this N load, if any
  114. static constexpr int NumMmaThreads = size(typename Ktraits::TiledMma0{});
  115. using MainloopPipeline = typename Ktraits::MainloopPipeline;
  116. using MainloopPipelineNoTMA = typename Ktraits::MainloopPipelineNoTMA;
  117. using PipelineParams = typename MainloopPipeline::Params;
  118. using PipelineState = typename MainloopPipeline::PipelineState;
  119. // Set the bytes transferred in this TMA transaction (may involve multiple issues)
  120. static constexpr uint32_t TmaTransactionBytesQ = static_cast<uint32_t>(size(SmemLayoutQ{}) * cutlass::sizeof_bits_v<Element> / 8);
  121. static constexpr uint32_t TmaTransactionBytesK = static_cast<uint32_t>(size(take<0, 2>(SmemLayoutK{})) * cutlass::sizeof_bits_v<Element> / 8);
  122. // static constexpr bool UseSchedulerBarrier = kHeadDim <= 128;
  123. static constexpr bool UseSchedulerBarrier = Ktraits::kNWarps >= 12 &&
  124. (cutlass::sizeof_bits_v<Element> == 8 ? kHeadDim >= 128 : kHeadDim <= 128);
  125. // Host side kernel arguments
  126. struct Arguments {
  127. Element const* ptr_Q;
  128. typename Seqlen_traits_Q::LayoutT layout_Q;
  129. Element const* ptr_K;
  130. typename Seqlen_traits::LayoutT layout_K;
  131. Element const* ptr_V;
  132. typename Seqlen_traits::LayoutT layout_V;
  133. float const softmax_scale_log2;
  134. float const* descale_q_ptr;
  135. float const* descale_k_ptr;
  136. float const* descale_v_ptr;
  137. int window_size_left;
  138. int window_size_right;
  139. int const qhead_per_khead;
  140. int const* cache_batch_idx;
  141. int const num_splits;
  142. };
  143. // Device side kernel params
  144. struct Params {
  145. typename Seqlen_traits_Q::LayoutT layout_Q;
  146. typename Seqlen_traits::LayoutT layout_K;
  147. typename Seqlen_traits::LayoutT layout_V;
  148. cutlass::FastDivmod qhead_per_khead_divmod;
  149. TMA_Q tma_load_Q;
  150. TMA_K tma_load_K;
  151. TMA_V tma_load_V;
  152. float const softmax_scale_log2;
  153. float const* descale_q_ptr;
  154. float const* descale_k_ptr;
  155. float const* descale_v_ptr;
  156. int window_size_left;
  157. int window_size_right;
  158. int const* cache_batch_idx;
  159. cutlass::FastDivmod num_splits_divmod;
  160. };
  161. static Params
  162. to_underlying_arguments(Arguments const& args) {
  163. Tensor mQ = make_tensor(make_gmem_ptr(args.ptr_Q), args.layout_Q);
  164. TMA_Q tma_load_Q = make_tma_copy(
  165. GmemTiledCopyQ{},
  166. mQ,
  167. SmemLayoutQCopy{},
  168. TileShapeQCopy{},
  169. _1{}); // no mcast for Q
  170. Tensor mK = make_tensor(make_gmem_ptr(args.ptr_K), args.layout_K);
  171. TMA_K tma_load_K = make_tma_copy(
  172. GmemTiledCopyKV{},
  173. mK,
  174. SmemLayoutK{}(_, _, _0{}),
  175. select<1, 2>(TileShape_MNK{}),
  176. size<0>(ClusterShape{})); // mcast along M mode for this N load, if any
  177. Tensor mV = make_tensor(make_gmem_ptr(args.ptr_V), args.layout_V);
  178. TMA_V tma_load_V = make_tma_copy(
  179. GmemTiledCopyKV{},
  180. mV,
  181. SmemLayoutV{}(_, _, _0{}),
  182. select<1, 2>(TileShape_MNK{}),
  183. size<0>(ClusterShape{})); // mcast along M mode for this N load, if any
  184. return {args.layout_Q, args.layout_K, args.layout_V,
  185. cutlass::FastDivmod(args.qhead_per_khead),
  186. tma_load_Q, tma_load_K, tma_load_V,
  187. args.softmax_scale_log2,
  188. args.descale_q_ptr, args.descale_k_ptr, args.descale_v_ptr,
  189. args.window_size_left, args.window_size_right,
  190. args.cache_batch_idx,
  191. cutlass::FastDivmod(args.num_splits)};
  192. }
  193. /// Issue Tma Descriptor Prefetch -- ideally from a single thread for best performance
  194. CUTLASS_DEVICE
  195. static void prefetch_tma_descriptors(Params const& mainloop_params) {
  196. cute::prefetch_tma_descriptor(mainloop_params.tma_load_Q.get_tma_descriptor());
  197. cute::prefetch_tma_descriptor(mainloop_params.tma_load_K.get_tma_descriptor());
  198. cute::prefetch_tma_descriptor(mainloop_params.tma_load_V.get_tma_descriptor());
  199. }
  200. CUTLASS_DEVICE
  201. void get_n_block_min_max(
  202. Params const& mainloop_params,
  203. int m_block,
  204. int n_split_idx,
  205. const Seqlen_traits_Q& seqlen_traits_q,
  206. const Seqlen_traits& seqlen_traits_k,
  207. int& n_block_min,
  208. int& n_block_max
  209. ) {
  210. // static constexpr int kBlockM = get<0>(TileShape_MNK{});
  211. static constexpr int kBlockN = get<1>(TileShape_MNK{});
  212. static constexpr int kBlockM_div_H = get<0>(TileShape_MNK{})/Ktraits::kBlockH;
  213. int const seqlen_q = seqlen_traits_q.actual_seq_len;
  214. int const seqlen_k = seqlen_traits_k.actual_seq_len;
  215. n_block_max = cute::ceil_div(seqlen_k, kBlockN);
  216. if constexpr(Is_split) {
  217. int const n_blocks_per_split
  218. = mainloop_params.num_splits_divmod.divide(n_block_max + int(mainloop_params.num_splits_divmod) - 1);
  219. n_block_min = n_split_idx * n_blocks_per_split;
  220. n_block_max = std::min(n_block_max, (n_split_idx + 1) * n_blocks_per_split);
  221. }
  222. if constexpr (Is_causal) {
  223. n_block_max = std::min(
  224. n_block_max,
  225. cute::ceil_div((m_block + 1) * kBlockM_div_H + seqlen_k - seqlen_q, kBlockN));
  226. } else if constexpr (Is_local) {
  227. n_block_max = std::min(
  228. n_block_max,
  229. cute::ceil_div((m_block + 1) * kBlockM_div_H + seqlen_k - seqlen_q + mainloop_params.window_size_right, kBlockN));
  230. n_block_min = std::max(
  231. n_block_min,
  232. (m_block * kBlockM_div_H + seqlen_k - seqlen_q - mainloop_params.window_size_left) / kBlockN);
  233. }
  234. }
  235. CUTLASS_DEVICE
  236. void get_n_block_max(
  237. Params const& mainloop_params,
  238. int m_block,
  239. const Seqlen_traits_Q& seqlen_traits_q,
  240. const Seqlen_traits& seqlen_traits_k,
  241. int& n_block_max
  242. ) {
  243. // static constexpr int kBlockM = get<0>(TileShape_MNK{});
  244. static constexpr int kBlockN = get<1>(TileShape_MNK{});
  245. static constexpr int kBlockM_div_H = get<0>(TileShape_MNK{})/Ktraits::kBlockH;
  246. int const seqlen_q = seqlen_traits_q.actual_seq_len;
  247. int const seqlen_k = seqlen_traits_k.actual_seq_len;
  248. n_block_max = cute::ceil_div(seqlen_k, kBlockN);
  249. if constexpr (Is_causal) {
  250. n_block_max = std::min(n_block_max,
  251. cute::ceil_div((m_block + 1) * kBlockM_div_H + seqlen_k - seqlen_q, kBlockN));
  252. }
  253. }
  254. template <typename Scheduler, typename SharedStorage>
  255. CUTLASS_DEVICE void
  256. load(Params const& mainloop_params,
  257. MainloopPipeline pipeline_k,
  258. MainloopPipeline pipeline_v,
  259. PipelineState& smem_pipe_write_k,
  260. PipelineState& smem_pipe_write_v,
  261. SharedStorage &shared_storage,
  262. Scheduler& scheduler,
  263. typename Scheduler::Params const& scheduler_params,
  264. typename Scheduler::WorkTileInfo& work_tile_info,
  265. cute::tuple<int32_t, int32_t, int32_t, int32_t> block_coord,
  266. int work_idx,
  267. const Seqlen_traits_Q& seqlen_traits_q,
  268. const Seqlen_traits& seqlen_traits_k,
  269. int n_block_min,
  270. int n_block_max
  271. ) {
  272. Tensor sQ = make_tensor(make_smem_ptr(shared_storage.smem_q.data()), SmemLayoutQCopy{});
  273. Tensor sK = make_tensor(make_smem_ptr(shared_storage.smem_k.data()), SmemLayoutK{});
  274. Tensor sV = make_tensor(make_smem_ptr(shared_storage.smem_v.data()), SmemLayoutV{});
  275. Tensor mQ = mainloop_params.tma_load_Q.get_tma_tensor(mainloop_params.layout_Q.shape());
  276. Tensor mK = mainloop_params.tma_load_K.get_tma_tensor(mainloop_params.layout_K.shape());
  277. Tensor mV = mainloop_params.tma_load_V.get_tma_tensor(mainloop_params.layout_V.shape());
  278. auto [m_block, n_split_idx, bidh, bidb] = block_coord;
  279. const int bidb_cache = mainloop_params.cache_batch_idx == nullptr ? bidb : mainloop_params.cache_batch_idx[bidb];
  280. const int bidh_kv = mainloop_params.qhead_per_khead_divmod.divide(bidh);
  281. // Prepare the TMA loads
  282. uint32_t block_rank_in_cluster = cute::block_rank_in_cluster();
  283. constexpr uint32_t cluster_shape_x = get<0>(ClusterShape());
  284. uint2 cluster_local_block_id = {block_rank_in_cluster % cluster_shape_x, block_rank_in_cluster / cluster_shape_x};
  285. Tensor gQ = [&] {
  286. // Need this inside lambda to capture structured binding
  287. auto [m_block, n_split_idx, bidh, bidb] = block_coord;
  288. if constexpr(Seqlen_traits_Q::UseGQAPacking) {
  289. return seqlen_traits_q.get_local_tile_tensor(
  290. mQ, TileShapeQCopy{}, bidh_kv, bidb)
  291. (_, _, _, m_block, bidh % int(mainloop_params.qhead_per_khead_divmod)); // (M/H, H, K)
  292. } else {
  293. return seqlen_traits_q.get_local_tile_tensor(
  294. mQ, TileShapeQCopy{}, bidh, bidb)(_, _, m_block); // (M, K)
  295. }
  296. }();
  297. Tensor gK = seqlen_traits_k.get_local_tile_tensor(
  298. mK, select<1, 2>(TileShape_MNK{}), bidh_kv, bidb_cache); // (N, K, _)
  299. Tensor gV = seqlen_traits_k.get_local_tile_tensor(
  300. mV, select<1, 2>(TileShape_MNK{}), bidh_kv, bidb_cache); // (N, K, _)
  301. Tensor sQ_x = make_tensor(sQ.data(), make_layout(sQ.layout(), Layout<_1>{}));
  302. Tensor gQ_x = make_tensor(gQ.data(), make_layout(gQ.layout(), Layout<_1>{}));
  303. auto [tQgQ, tQsQ] = tma_partition(mainloop_params.tma_load_Q, _0{}, Layout<_1>{},
  304. group_modes<0, 2>(sQ_x), group_modes<0, 2>(gQ_x)); // (TMA), (TMA)
  305. auto [tKgK, tKsK] = tma_partition(mainloop_params.tma_load_K, block_rank_in_cluster, Layout<ClusterShape>{},
  306. group_modes<0, 2>(sK), group_modes<0, 2>(gK)); // (TMA, k), (TMA, PIPE)
  307. auto [tVgV, tVsV] = tma_partition(mainloop_params.tma_load_V, block_rank_in_cluster, Layout<ClusterShape>{},
  308. group_modes<0, 2>(sV), group_modes<0, 2>(gV)); // (TMA, k), (TMA, PIPE)
  309. uint16_t mcast_mask_kv = 0;
  310. if constexpr (cute::is_same_v<GmemTiledCopyKV, SM90_TMA_LOAD_MULTICAST>) {
  311. auto block_layout = Layout<ClusterShape>{}; // (m,n) -> block_id
  312. for (int m = 0; m < size<0>(block_layout); ++m) {
  313. mcast_mask_kv |= (uint16_t(1) << block_layout(m, cluster_local_block_id.y, _0{}));
  314. }
  315. }
  316. int n_block = n_block_max - 1;
  317. int lane_predicate = cute::elect_one_sync();
  318. if (lane_predicate) {
  319. pipeline_k.producer_acquire(smem_pipe_write_k);
  320. copy(mainloop_params.tma_load_K.with(*pipeline_k.producer_get_barrier(smem_pipe_write_k), mcast_mask_kv),
  321. tKgK(_, n_block), tKsK(_, smem_pipe_write_k.index()));
  322. ++smem_pipe_write_k;
  323. }
  324. // Wait for the MMA warpgroups to say that smem_q is ready
  325. cutlass::arch::NamedBarrier::sync(NumMmaThreads + cutlass::NumThreadsPerWarp, static_cast<int>(FwdNamedBarriers::QueryEmpty) /*id*/);
  326. if (lane_predicate) {
  327. shared_storage.barrier_Q.arrive_and_expect_tx(TmaTransactionBytesQ);
  328. copy(mainloop_params.tma_load_Q.with(reinterpret_cast<cutlass::arch::ClusterTransactionBarrier::ValueType&>(shared_storage.barrier_Q), 0 /*mcast_mask*/), tQgQ, tQsQ);
  329. }
  330. // Wait for warp 1 to signal that smem_v are ready and V can be copied from gmem
  331. // Need ClusterBarrier, not just NamedBarrier. Otherwise we might have CTA 0 finishing the
  332. // TMA store on O first, call TMA multicast load on V, before CTA 1 can finishing TMA store on O.
  333. if constexpr (!No_smem_O) {
  334. shared_storage.barrier_O.wait((work_idx + 1) % 2);
  335. // if constexpr(!seqlen_traits_q.UseVarSeqLen) {
  336. // shared_storage.barrier_O.wait((work_idx + 1) % 2);
  337. // } else {
  338. // // Wait for the MMA warpgroups to say that smem_o is ready
  339. // cutlass::arch::NamedBarrier::sync(NumMmaThreads + cutlass::NumThreadsPerWarp, static_cast<int>(FwdNamedBarriers::OutputEmpty) /*id*/);
  340. // }
  341. }
  342. if (lane_predicate) {
  343. // CUTLASS_PRAGMA_NO_UNROLL
  344. #pragma unroll 2
  345. for (; n_block > n_block_min; --n_block) {
  346. pipeline_k.producer_acquire(smem_pipe_write_k);
  347. copy(mainloop_params.tma_load_K.with(*pipeline_k.producer_get_barrier(smem_pipe_write_k), mcast_mask_kv),
  348. tKgK(_, n_block - 1), tKsK(_, smem_pipe_write_k.index()));
  349. ++smem_pipe_write_k;
  350. pipeline_v.producer_acquire(smem_pipe_write_v);
  351. copy(mainloop_params.tma_load_V.with(*pipeline_v.producer_get_barrier(smem_pipe_write_v), mcast_mask_kv),
  352. tVgV(_, n_block), tVsV(_, smem_pipe_write_v.index()));
  353. ++smem_pipe_write_v;
  354. }
  355. }
  356. scheduler.prefetch_next_work(scheduler_params, work_tile_info);
  357. if (lane_predicate) {
  358. pipeline_v.producer_acquire(smem_pipe_write_v);
  359. copy(mainloop_params.tma_load_V.with(*pipeline_v.producer_get_barrier(smem_pipe_write_v), mcast_mask_kv),
  360. tVgV(_, n_block), tVsV(_, smem_pipe_write_v.index()));
  361. ++smem_pipe_write_v;
  362. }
  363. scheduler.broadcast_next_work(work_tile_info);
  364. }
  365. template <typename Scheduler, typename SharedStorage>
  366. CUTLASS_DEVICE void
  367. load_fp8(Params const& mainloop_params,
  368. MainloopPipeline pipeline_k,
  369. MainloopPipeline pipeline_v,
  370. MainloopPipelineNoTMA pipeline_vt,
  371. PipelineState& smem_pipe_write,
  372. PipelineState& smem_pipe_read,
  373. SharedStorage &shared_storage,
  374. Scheduler& scheduler,
  375. typename Scheduler::Params const& scheduler_params,
  376. typename Scheduler::WorkTileInfo& work_tile_info,
  377. cute::tuple<int32_t, int32_t, int32_t, int32_t> block_coord,
  378. int work_idx,
  379. const Seqlen_traits_Q& seqlen_traits_q,
  380. const Seqlen_traits& seqlen_traits_k,
  381. int n_block_min,
  382. int n_block_max
  383. ) {
  384. using SmemLayoutTransposeV = typename Ktraits::SmemLayoutTransposeV;
  385. using SmemLayoutTransposeVt = typename Ktraits::SmemLayoutTransposeVt;
  386. Tensor sQ = make_tensor(make_smem_ptr(shared_storage.smem_q.data()), SmemLayoutQCopy{});
  387. Tensor sK = make_tensor(make_smem_ptr(shared_storage.smem_k.data()), SmemLayoutK{});
  388. Tensor sV = make_tensor(make_smem_ptr(shared_storage.smem_v.data()), SmemLayoutV{});
  389. Tensor sV_divide = as_position_independent_swizzle_tensor(make_tensor(make_smem_ptr(shared_storage.smem_v.data()), SmemLayoutTransposeV{}));
  390. Tensor sVt_divide = as_position_independent_swizzle_tensor(make_tensor(make_smem_ptr(shared_storage.smem_v_out.data()), SmemLayoutTransposeVt{}));
  391. auto smem_transpose_V = SmemTransposeFp8_64x64();
  392. auto do_transpose_V = [&](int stage) {
  393. CUTLASS_PRAGMA_UNROLL
  394. for (int j = 0; j < shape<2>(SmemLayoutTransposeV{}); ++j) {
  395. CUTLASS_PRAGMA_UNROLL
  396. for (int i = 0; i < shape<1>(SmemLayoutTransposeV{}); ++i) {
  397. smem_transpose_V(flatten(sV_divide(_, i, j, stage)),
  398. flatten(sVt_divide(_, i, j, stage)));
  399. }
  400. }
  401. cutlass::arch::fence_view_async_shared();
  402. cutlass::arch::NamedBarrier::sync(cutlass::NumThreadsPerWarpGroup, static_cast<int>(FwdNamedBarriers::ProducerWG) /*id*/);
  403. };
  404. Tensor mQ = mainloop_params.tma_load_Q.get_tma_tensor(mainloop_params.layout_Q.shape());
  405. Tensor mK = mainloop_params.tma_load_K.get_tma_tensor(mainloop_params.layout_K.shape());
  406. Tensor mV = mainloop_params.tma_load_V.get_tma_tensor(mainloop_params.layout_V.shape());
  407. auto [m_block, split_idx, bidh, bidb] = block_coord;
  408. const int bidb_cache = mainloop_params.cache_batch_idx == nullptr ? bidb : mainloop_params.cache_batch_idx[bidb];
  409. const int bidh_kv = mainloop_params.qhead_per_khead_divmod.divide(bidh);
  410. // Prepare the TMA loads
  411. uint32_t block_rank_in_cluster = cute::block_rank_in_cluster();
  412. constexpr uint32_t cluster_shape_x = get<0>(ClusterShape());
  413. uint2 cluster_local_block_id = {block_rank_in_cluster % cluster_shape_x, block_rank_in_cluster / cluster_shape_x};
  414. Tensor gQ = [&] {
  415. // Need this inside lambda to capture structured binding
  416. auto [m_block, n_split_idx, bidh, bidb] = block_coord;
  417. if constexpr(Seqlen_traits_Q::UseGQAPacking) {
  418. return seqlen_traits_q.get_local_tile_tensor(
  419. mQ, TileShapeQCopy{}, bidh_kv, bidb)
  420. (_, _, _, m_block, bidh % int(mainloop_params.qhead_per_khead_divmod)); // (M/H, H, K)
  421. } else {
  422. return seqlen_traits_q.get_local_tile_tensor(
  423. mQ, TileShapeQCopy{}, bidh, bidb)(_, _, m_block); // (M, K)
  424. }
  425. }();
  426. Tensor gK = seqlen_traits_k.get_local_tile_tensor(
  427. mK, select<1, 2>(TileShape_MNK{}), bidh_kv, bidb_cache); // (N, K, _)
  428. Tensor gV = seqlen_traits_k.get_local_tile_tensor(
  429. mV, select<1, 2>(TileShape_MNK{}), bidh_kv, bidb_cache); // (N, K, _)
  430. Tensor sQ_x = make_tensor(sQ.data(), make_layout(sQ.layout(), Layout<_1>{}));
  431. Tensor gQ_x = make_tensor(gQ.data(), make_layout(gQ.layout(), Layout<_1>{}));
  432. auto [tQgQ, tQsQ] = tma_partition(mainloop_params.tma_load_Q, _0{}, Layout<_1>{},
  433. group_modes<0, 2>(sQ_x), group_modes<0, 2>(gQ_x)); // (TMA), (TMA)
  434. auto [tKgK, tKsK] = tma_partition(mainloop_params.tma_load_K, block_rank_in_cluster, Layout<ClusterShape>{},
  435. group_modes<0, 2>(sK), group_modes<0, 2>(gK)); // (TMA, k), (TMA, PIPE)
  436. auto [tVgV, tVsV] = tma_partition(mainloop_params.tma_load_V, block_rank_in_cluster, Layout<ClusterShape>{},
  437. group_modes<0, 2>(sV), group_modes<0, 2>(gV)); // (TMA, k), (TMA, PIPE)
  438. uint16_t mcast_mask_kv = 0;
  439. if constexpr (cute::is_same_v<GmemTiledCopyKV, SM90_TMA_LOAD_MULTICAST>) {
  440. auto block_layout = Layout<ClusterShape>{}; // (m,n) -> block_id
  441. for (int m = 0; m < size<0>(block_layout); ++m) {
  442. mcast_mask_kv |= (uint16_t(1) << block_layout(m, cluster_local_block_id.y, _0{}));
  443. }
  444. }
  445. int n_block = n_block_max - 1;
  446. int lane_predicate = cute::elect_one_sync();
  447. int warp_idx_in_warpgroup = __shfl_sync(0xffffffff, (threadIdx.x / 32) % 4, 0);
  448. if (warp_idx_in_warpgroup == 0 && lane_predicate) {
  449. pipeline_k.producer_acquire(smem_pipe_write);
  450. copy(mainloop_params.tma_load_K.with(*pipeline_k.producer_get_barrier(smem_pipe_write), mcast_mask_kv),
  451. tKgK(_, n_block), tKsK(_, smem_pipe_write.index()));
  452. }
  453. // Wait for the MMA warpgroups to say that smem_q is ready
  454. // for fp8, change from NumThreadsPerWarp to NumThreadsPerWarpGroup
  455. cutlass::arch::NamedBarrier::sync(NumMmaThreads + cutlass::NumThreadsPerWarpGroup, static_cast<int>(FwdNamedBarriers::QueryEmpty) /*id*/);
  456. if (warp_idx_in_warpgroup == 0 && lane_predicate) {
  457. shared_storage.barrier_Q.arrive_and_expect_tx(TmaTransactionBytesQ);
  458. copy(mainloop_params.tma_load_Q.with(reinterpret_cast<cutlass::arch::ClusterTransactionBarrier::ValueType&>(shared_storage.barrier_Q), 0 /*mcast_mask*/), tQgQ, tQsQ);
  459. if constexpr(!Ktraits::VO_union_all) {
  460. pipeline_v.producer_acquire(smem_pipe_write);
  461. copy(mainloop_params.tma_load_V.with(*pipeline_v.producer_get_barrier(smem_pipe_write), mcast_mask_kv),
  462. tVgV(_, n_block), tVsV(_, smem_pipe_write.index()));
  463. }
  464. }
  465. // With fp8 kernel, smem_o is in union with smem_v_out,
  466. // except for split kernel + hdim 256,
  467. // so could use NamedBarrier instead of ClusterBarrier.
  468. // But, this doesn't appear to have any benefit.
  469. if constexpr (!No_smem_O) {
  470. shared_storage.barrier_O.wait((work_idx + 1) % 2);
  471. // if constexpr(!seqlen_traits_q.UseVarSeqLen) {
  472. // shared_storage.barrier_O.wait((work_idx + 1) % 2);
  473. // } else {
  474. // // Wait for the MMA warpgroups to say that smem_o is empty
  475. // cutlass::arch::NamedBarrier::sync(NumMmaThreads + cutlass::NumThreadsPerWarpGroup, static_cast<int>(FwdNamedBarriers::OutputEmpty) /*id*/);
  476. // // shared_storage.barrier_O.wait((work_idx + 1) % 2);
  477. // }
  478. }
  479. if constexpr(Ktraits::VO_union_all) {
  480. if (warp_idx_in_warpgroup == 0 && lane_predicate) {
  481. pipeline_v.producer_acquire(smem_pipe_write);
  482. copy(mainloop_params.tma_load_V.with(*pipeline_v.producer_get_barrier(smem_pipe_write), mcast_mask_kv),
  483. tVgV(_, n_block), tVsV(_, smem_pipe_write.index()));
  484. }
  485. }
  486. #pragma unroll 2
  487. for (; n_block > n_block_min; --n_block) {
  488. pipeline_v.consumer_wait(smem_pipe_read);
  489. pipeline_vt.producer_acquire(smem_pipe_write);
  490. do_transpose_V(smem_pipe_read.index());
  491. pipeline_vt.producer_commit(smem_pipe_write);
  492. pipeline_v.consumer_release(smem_pipe_read);
  493. ++smem_pipe_write;
  494. ++smem_pipe_read;
  495. if (warp_idx_in_warpgroup == 0 && lane_predicate) {
  496. pipeline_k.producer_acquire(smem_pipe_write);
  497. copy(mainloop_params.tma_load_K.with(*pipeline_k.producer_get_barrier(smem_pipe_write), mcast_mask_kv),
  498. tKgK(_, n_block-1), tKsK(_, smem_pipe_write.index()));
  499. pipeline_v.producer_acquire(smem_pipe_write);
  500. copy(mainloop_params.tma_load_V.with(*pipeline_v.producer_get_barrier(smem_pipe_write), mcast_mask_kv),
  501. tVgV(_, n_block-1), tVsV(_, smem_pipe_write.index()));
  502. }
  503. }
  504. scheduler.prefetch_next_work(scheduler_params, work_tile_info);
  505. scheduler.broadcast_next_work(work_tile_info);
  506. pipeline_v.consumer_wait(smem_pipe_read);
  507. pipeline_vt.producer_acquire(smem_pipe_write);
  508. do_transpose_V(smem_pipe_read.index());
  509. pipeline_vt.producer_commit(smem_pipe_write);
  510. pipeline_v.consumer_release(smem_pipe_read);
  511. ++smem_pipe_write;
  512. ++smem_pipe_read;
  513. }
  514. /// Perform a Producer Epilogue to prevent early exit of blocks in a Cluster
  515. CUTLASS_DEVICE void
  516. load_tail(MainloopPipeline pipeline_k, MainloopPipeline pipeline_v,
  517. PipelineState& smem_pipe_write_k, PipelineState& smem_pipe_write_v) {
  518. int lane_predicate = cute::elect_one_sync();
  519. int warp_idx_in_warpgroup = __shfl_sync(0xffffffff, (threadIdx.x / 32) % 4, 0);
  520. // Issue the epilogue waits
  521. if (warp_idx_in_warpgroup == 0 && lane_predicate) {
  522. /* This helps avoid early exit of blocks in Cluster
  523. * Waits for all stages to either be released (all Consumer UNLOCKs), or if the stage was never used
  524. * then would just be acquired since the phase was still inverted from make_producer_start_state
  525. */
  526. pipeline_k.producer_tail(smem_pipe_write_k);
  527. pipeline_v.producer_tail(smem_pipe_write_v);
  528. }
  529. }
  530. /// Perform a Producer Epilogue to prevent early exit of blocks in a Cluster
  531. CUTLASS_DEVICE void
  532. load_tail_one_write(MainloopPipeline pipeline_k, MainloopPipeline pipeline_v,
  533. PipelineState& smem_pipe_write) {
  534. int lane_predicate = cute::elect_one_sync();
  535. int warp_idx_in_warpgroup = __shfl_sync(0xffffffff, (threadIdx.x / 32) % 4, 0);
  536. // Issue the epilogue waits
  537. if (warp_idx_in_warpgroup == 0 && lane_predicate) {
  538. /* This helps avoid early exit of blocks in Cluster
  539. * Waits for all stages to either be released (all Consumer UNLOCKs), or if the stage was never used
  540. * then would just be acquired since the phase was still inverted from make_producer_start_state
  541. */
  542. pipeline_k.producer_tail(smem_pipe_write);
  543. pipeline_v.producer_tail(smem_pipe_write);
  544. }
  545. }
  546. CUTLASS_DEVICE void
  547. warp_scheduler_barrier_sync() {
  548. if constexpr (UseSchedulerBarrier) {
  549. cutlass::arch::NamedBarrier::sync(NumMmaThreads, static_cast<int>(FwdNamedBarriers::WarpSchedulerWG1) - 1 + cutlass::canonical_warp_group_idx() /*id*/);
  550. }
  551. }
  552. CUTLASS_DEVICE void
  553. warp_scheduler_barrier_arrive() {
  554. if constexpr (!UseSchedulerBarrier) {
  555. return;
  556. } else {
  557. static_assert(NumMmaThreads == 2 * cutlass::NumThreadsPerWarpGroup || NumMmaThreads == 3 * cutlass::NumThreadsPerWarpGroup);
  558. if constexpr (NumMmaThreads == 2 * cutlass::NumThreadsPerWarpGroup) {
  559. cutlass::arch::NamedBarrier::arrive(NumMmaThreads, static_cast<int>(FwdNamedBarriers::WarpSchedulerWG1) - 1 + (3 - cutlass::canonical_warp_group_idx()) /*id*/);
  560. } else {
  561. cutlass::arch::NamedBarrier::arrive(NumMmaThreads, static_cast<int>(FwdNamedBarriers::WarpSchedulerWG1) - 1 + (cutlass::canonical_warp_group_idx() <= 2 ? cutlass::canonical_warp_group_idx() + 1 : cutlass::canonical_warp_group_idx() + 1 - 3) /*id*/);
  562. cutlass::arch::NamedBarrier::arrive(NumMmaThreads, static_cast<int>(FwdNamedBarriers::WarpSchedulerWG1) - 1 + (cutlass::canonical_warp_group_idx() <= 1 ? cutlass::canonical_warp_group_idx() + 2 : cutlass::canonical_warp_group_idx() + 2 - 3) /*id*/);
  563. }
  564. }
  565. }
  566. CUTLASS_DEVICE void
  567. mma_init() {
  568. // Tell producer (warp 0) that smem_q is ready
  569. cutlass::arch::NamedBarrier::arrive(NumMmaThreads + Ktraits::NumProducerThreads, static_cast<int>(FwdNamedBarriers::QueryEmpty) /*id*/);
  570. if constexpr (!UseSchedulerBarrier) {
  571. return;
  572. } else {
  573. static_assert(NumMmaThreads == 2 * cutlass::NumThreadsPerWarpGroup || NumMmaThreads == 3 * cutlass::NumThreadsPerWarpGroup);
  574. if (cutlass::canonical_warp_group_idx() > 1) {
  575. cutlass::arch::NamedBarrier::arrive(NumMmaThreads, static_cast<int>(FwdNamedBarriers::WarpSchedulerWG1) - 1 + 1 /*id*/);
  576. }
  577. if constexpr (NumMmaThreads == 3 * cutlass::NumThreadsPerWarpGroup) {
  578. if (cutlass::canonical_warp_group_idx() > 2) {
  579. cutlass::arch::NamedBarrier::arrive(NumMmaThreads, static_cast<int>(FwdNamedBarriers::WarpSchedulerWG1) - 1 + 2 /*id*/);
  580. }
  581. }
  582. }
  583. }
  584. template <typename SharedStorage, typename FrgTensorO, typename Softmax>
  585. CUTLASS_DEVICE void
  586. mma(Params const& mainloop_params,
  587. MainloopPipeline pipeline_k,
  588. MainloopPipeline pipeline_v,
  589. PipelineState& smem_pipe_read_k,
  590. PipelineState& smem_pipe_read_v,
  591. FrgTensorO& tOrO,
  592. Softmax& softmax,
  593. int n_block_min,
  594. int n_block_max,
  595. int thread_idx,
  596. int work_idx,
  597. int m_block,
  598. SharedStorage& shared_storage,
  599. const Seqlen_traits_Q& seqlen_traits_q,
  600. const Seqlen_traits& seqlen_traits_k
  601. ) {
  602. static_assert(is_rmem<FrgTensorO>::value, "O tensor must be rmem resident.");
  603. static constexpr int kBlockN = get<1>(TileShape_MNK{});
  604. static constexpr int kBlockH = Ktraits::kBlockH;
  605. static constexpr int kBlockM_div_H = get<0>(TileShape_MNK{}) / kBlockH;
  606. Tensor sQ = make_tensor(make_smem_ptr(shared_storage.smem_q.data()), SmemLayoutQ{});
  607. Tensor sK = make_tensor(make_smem_ptr(shared_storage.smem_k.data()), SmemLayoutK{});
  608. Tensor sVt = make_tensor(make_smem_ptr(shared_storage.smem_v.data()), SmemLayoutVt{});
  609. typename Ktraits::TiledMma0 tiled_mma0;
  610. typename Ktraits::TiledMma1 tiled_mma1;
  611. auto threadMma0 = tiled_mma0.get_thread_slice(thread_idx);
  612. auto threadMma1 = tiled_mma1.get_thread_slice(thread_idx);
  613. // Allocate "fragments/descriptors" for first matmul.
  614. Tensor tSrQ = threadMma0.partition_fragment_A(sQ);
  615. Tensor tSrK = threadMma0.partition_fragment_B(sK);
  616. // Allocate "fragments/descriptors" for second matmul.
  617. // Note: S becomes P.
  618. Tensor tOrV = threadMma1.partition_fragment_B(sVt);
  619. auto consumer_wait = [](auto& pipeline, auto& smem_pipe_read) {
  620. auto barrier_token = pipeline.consumer_try_wait(smem_pipe_read);
  621. pipeline.consumer_wait(smem_pipe_read, barrier_token);
  622. };
  623. tiled_mma1.accumulate_ = GMMA::ScaleOut::Zero;
  624. int const seqlen_q = seqlen_traits_q.actual_seq_len;
  625. int const seqlen_k = seqlen_traits_k.actual_seq_len;
  626. int n_block = n_block_max - 1;
  627. cutlass::ConsumerToken barrier_token = static_cast<cutlass::BarrierStatus>(shared_storage.barrier_Q.try_wait(work_idx % 2));
  628. if (barrier_token == cutlass::BarrierStatus::WaitAgain) { shared_storage.barrier_Q.wait(work_idx % 2); }
  629. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  630. consumer_wait(pipeline_k, smem_pipe_read_k);
  631. warp_scheduler_barrier_sync();
  632. flash::gemm</*zero_init=*/true, /*wg_wait=*/-1>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read_k.index()), tSrS);
  633. warp_scheduler_barrier_arrive();
  634. // if constexpr (!No_smem_O && !seqlen_traits_q.UseVarSeqLen) {
  635. if constexpr (!No_smem_O) {
  636. if (work_idx != 0) {
  637. int lane_predicate = cute::elect_one_sync();
  638. if (cutlass::canonical_warp_idx_sync() == Ktraits::kNWarps - 1 && lane_predicate) {
  639. tma_store_wait<0>();
  640. #pragma unroll
  641. for (uint32_t cta_id = 0; cta_id < size(ClusterShape{}); ++cta_id) {
  642. shared_storage.barrier_O.arrive(cta_id, lane_predicate);
  643. }
  644. }
  645. }
  646. }
  647. warpgroup_wait<0>();
  648. pipeline_k.consumer_release(smem_pipe_read_k);
  649. ++smem_pipe_read_k;
  650. auto col_limit_right = [&](int row, int n_block) {
  651. int col_limit_base = row + 1 + seqlen_k - n_block * kBlockN - seqlen_q + m_block * kBlockM_div_H;
  652. if constexpr(Is_local)
  653. return col_limit_base + mainloop_params.window_size_right;
  654. else
  655. return col_limit_base;
  656. };
  657. auto col_limit_left = [&](int row, int n_block) {
  658. return std::max(
  659. 0,
  660. row + seqlen_k - n_block * kBlockN - seqlen_q + m_block * kBlockM_div_H - mainloop_params.window_size_left
  661. );
  662. };
  663. {
  664. Tensor cS = cute::make_identity_tensor(select<0, 1>(TileShape_MNK{}));
  665. Tensor tScS = threadMma0.partition_C(cS);
  666. #pragma unroll
  667. for (int i = 0; i < size(tSrS); ++i) {
  668. if constexpr (!Is_causal && !Is_local) { // Just masking based on col
  669. if (int(get<1>(tScS(i))) >= int(seqlen_k - n_block * kBlockN)) { tSrS(i) = -INFINITY; }
  670. } else { // mask based on both row and col
  671. // using std::min is faster than doing col >= limit0 or col >= limit1
  672. // Need to cast get<1>(tScS(i)) to (signed) int since by default it's unsigned, and the
  673. // right hand side can be negative and might be converted to a very large unsigned integer.
  674. int row = int(get<0>(tScS(i))) / kBlockH;
  675. if (int(get<1>(tScS(i))) >= std::min(seqlen_k - n_block * kBlockN, col_limit_right(row, n_block))) {
  676. tSrS(i) = -INFINITY;
  677. } else if constexpr(Is_local) {
  678. if (int(get<1>(tScS(i))) < col_limit_left(row, n_block)) {
  679. tSrS(i) = -INFINITY;
  680. }
  681. }
  682. }
  683. }
  684. }
  685. softmax.template online_softmax</*Is_first=*/true>(tSrS);
  686. Tensor tOrP = make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs<typename Ktraits::TiledMma1>(tSrS.layout()));
  687. Tensor scores_scale = make_fragment_like(softmax.row_max);
  688. clear(scores_scale);
  689. constexpr int n_masking_steps = !Is_causal ? 1 : cute::ceil_div(kBlockM_div_H, kBlockN) + 1;
  690. // Only go through these if Is_causal, since n_masking_steps = 1 when !Is_causal
  691. #pragma unroll
  692. for (int masking_step = 0; masking_step < n_masking_steps - 1 && n_block > n_block_min; ++masking_step, --n_block) {
  693. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  694. consumer_wait(pipeline_k, smem_pipe_read_k);
  695. warp_scheduler_barrier_sync();
  696. flash::gemm</*zero_init=*/true, /*wg_wait=*/-1>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read_k.index()), tSrS);
  697. if (masking_step > 0) { softmax.rescale_o(tOrO, scores_scale); }
  698. consumer_wait(pipeline_v, smem_pipe_read_v);
  699. flash::gemm</*zero_init=*/false, /*wg_wait=*/-1>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read_v.index()), tOrO);
  700. warp_scheduler_barrier_arrive();
  701. warpgroup_wait<1>();
  702. pipeline_k.consumer_release(smem_pipe_read_k); // release K
  703. Tensor cS = cute::make_identity_tensor(select<0, 1>(TileShape_MNK{}));
  704. Tensor tScS = threadMma0.partition_C(cS);
  705. #pragma unroll
  706. for (int i = 0; i < size(tSrS); ++i) {
  707. int row = int(get<0>(tScS(i))) / kBlockH;
  708. if (int(get<1>(tScS(i))) >= col_limit_right(row, n_block - 1)) {
  709. tSrS(i) = -INFINITY;
  710. }
  711. }
  712. cute::copy(softmax.template max</*Is_first=*/false, /*Check_inf=*/true>(tSrS), scores_scale);
  713. softmax.template online_softmax</*Is_first=*/false, /*Check_inf=*/true>(tSrS);
  714. warpgroup_wait<0>();
  715. pipeline_v.consumer_release(smem_pipe_read_v); // release V
  716. ++smem_pipe_read_k;
  717. ++smem_pipe_read_v;
  718. cute::copy(make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs<typename Ktraits::TiledMma1>(tSrS.layout())), tOrP);
  719. }
  720. #pragma unroll 1
  721. for (; n_block > n_block_min; --n_block) {
  722. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  723. consumer_wait(pipeline_k, smem_pipe_read_k);
  724. warp_scheduler_barrier_sync();
  725. flash::gemm</*zero_init=*/true, /*wg_wait=*/-1>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read_k.index()), tSrS);
  726. softmax.rescale_o(tOrO, scores_scale);
  727. consumer_wait(pipeline_v, smem_pipe_read_v);
  728. flash::gemm</*zero_init=*/false, /*wg_wait=*/-1>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read_v.index()), tOrO);
  729. warp_scheduler_barrier_arrive();
  730. warpgroup_wait<1>();
  731. pipeline_k.consumer_release(smem_pipe_read_k); // release K
  732. if constexpr(Is_local) {
  733. Tensor cS = cute::make_identity_tensor(select<0, 1>(TileShape_MNK{}));
  734. Tensor tScS = threadMma0.partition_C(cS);
  735. #pragma unroll
  736. for (int i = 0; i < size(tSrS); ++i) {
  737. int row = int(get<0>(tScS(i))) / kBlockH;
  738. if (
  739. int(get<1>(tScS(i))) >= col_limit_right(row, n_block - 1) ||
  740. int(get<1>(tScS(i))) < col_limit_left(row, n_block - 1)
  741. ) {
  742. tSrS(i) = -INFINITY;
  743. }
  744. }
  745. }
  746. // auto scores_scale = softmax.template max</*Is_first=*/false>(tSrS);
  747. cute::copy(softmax.template max</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS), scores_scale);
  748. softmax.template online_softmax</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS);
  749. warpgroup_wait<0>();
  750. pipeline_v.consumer_release(smem_pipe_read_v); // release V
  751. ++smem_pipe_read_k;
  752. ++smem_pipe_read_v;
  753. // softmax.rescale_o(tOrO, scores_scale);
  754. cute::copy(make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs<typename Ktraits::TiledMma1>(tSrS.layout())), tOrP);
  755. }
  756. // Tell warp 0 that smem_q is ready
  757. cutlass::arch::NamedBarrier::arrive(NumMmaThreads + cutlass::NumThreadsPerWarp, static_cast<int>(FwdNamedBarriers::QueryEmpty) /*id*/);
  758. softmax.rescale_o(tOrO, scores_scale);
  759. consumer_wait(pipeline_v, smem_pipe_read_v);
  760. flash::gemm</*zero_init=*/false, /*wg_wait=*/-1>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read_v.index()), tOrO);
  761. cute::copy(softmax.template finalize</*Is_dropout=*/false, Is_split>(tSrS), scores_scale);
  762. warpgroup_wait<0>();
  763. pipeline_v.consumer_release(smem_pipe_read_v); // release V, otherwise producers will hang
  764. ++smem_pipe_read_v;
  765. softmax.rescale_o(tOrO, scores_scale);
  766. return;
  767. }
  768. template <bool Delay_V_release = false, typename SharedStorage, typename FrgTensorO, typename Softmax>
  769. CUTLASS_DEVICE void
  770. mma_fp8(Params const& mainloop_params,
  771. MainloopPipeline pipeline_k,
  772. MainloopPipelineNoTMA pipeline_vt,
  773. PipelineState& smem_pipe_read,
  774. PipelineState& smem_pipe_release,
  775. FrgTensorO& tOrO,
  776. Softmax& softmax,
  777. int n_block_min,
  778. int n_block_max,
  779. int thread_idx,
  780. int work_idx,
  781. int m_block,
  782. SharedStorage& shared_storage,
  783. const Seqlen_traits_Q& seqlen_traits_q,
  784. const Seqlen_traits& seqlen_traits_k
  785. ) {
  786. static_assert(is_rmem<FrgTensorO>::value, "O tensor must be rmem resident.");
  787. // static constexpr int kBlockM = get<0>(TileShape_MNK{});
  788. static constexpr int kBlockN = get<1>(TileShape_MNK{});
  789. static constexpr int kBlockH = Ktraits::kBlockH;
  790. static constexpr int kBlockM_div_H = get<0>(TileShape_MNK{}) / kBlockH;
  791. Tensor sQ = make_tensor(make_smem_ptr(shared_storage.smem_q.data()), SmemLayoutQ{});
  792. Tensor sK = make_tensor(make_smem_ptr(shared_storage.smem_k.data()), SmemLayoutK{});
  793. Tensor sVt = make_tensor(make_smem_ptr(shared_storage.smem_v_out.data()), SmemLayoutVt{});
  794. typename Ktraits::TiledMma0 tiled_mma0;
  795. typename Ktraits::TiledMma1 tiled_mma1;
  796. auto threadMma0 = tiled_mma0.get_thread_slice(thread_idx);
  797. auto threadMma1 = tiled_mma1.get_thread_slice(thread_idx);
  798. // Allocate "fragments/descriptors" for first matmul.
  799. Tensor tSrQ = threadMma0.partition_fragment_A(sQ);
  800. Tensor tSrK = threadMma0.partition_fragment_B(sK);
  801. // Allocate "fragments/descriptors" for second matmul.
  802. Tensor tOrV = threadMma1.partition_fragment_B(sVt);
  803. auto consumer_wait = [](auto& pipeline, auto& smem_pipe_read) {
  804. auto barrier_token = pipeline.consumer_try_wait(smem_pipe_read);
  805. pipeline.consumer_wait(smem_pipe_read, barrier_token);
  806. };
  807. tiled_mma1.accumulate_ = GMMA::ScaleOut::Zero;
  808. int const seqlen_q = seqlen_traits_q.actual_seq_len;
  809. int const seqlen_k = seqlen_traits_k.actual_seq_len;
  810. int n_block = n_block_max - 1;
  811. cutlass::ConsumerToken barrier_token = static_cast<cutlass::BarrierStatus>(shared_storage.barrier_Q.try_wait(work_idx % 2));
  812. if (barrier_token == cutlass::BarrierStatus::WaitAgain) { shared_storage.barrier_Q.wait(work_idx % 2); }
  813. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  814. consumer_wait(pipeline_k, smem_pipe_read);
  815. warp_scheduler_barrier_sync();
  816. flash::gemm</*zero_init=*/true, /*wg_wait=*/-1>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read.index()), tSrS);
  817. if constexpr (!No_smem_O) {
  818. if (work_idx != 0) {
  819. int lane_predicate = cute::elect_one_sync();
  820. if (cutlass::canonical_warp_idx_sync() == Ktraits::kNWarps - 1 && lane_predicate) {
  821. tma_store_wait<0>();
  822. #pragma unroll
  823. for (uint32_t cta_id = 0; cta_id < size(ClusterShape{}); ++cta_id) {
  824. shared_storage.barrier_O.arrive(cta_id, lane_predicate);
  825. }
  826. }
  827. }
  828. }
  829. warpgroup_wait<0>();
  830. warp_scheduler_barrier_arrive();
  831. pipeline_k.consumer_release(smem_pipe_read);
  832. auto col_limit_right = [&](int row, int n_block) {
  833. int col_limit_base = row + 1 + seqlen_k - n_block * kBlockN - seqlen_q + m_block * kBlockM_div_H;
  834. if constexpr(Is_local)
  835. return col_limit_base + mainloop_params.window_size_right;
  836. else
  837. return col_limit_base;
  838. };
  839. auto col_limit_left = [&](int row, int n_block) {
  840. return std::max(
  841. 0,
  842. row + seqlen_k - n_block * kBlockN - seqlen_q + m_block * kBlockM_div_H - mainloop_params.window_size_left
  843. );
  844. };
  845. {
  846. Tensor cS = cute::make_identity_tensor(select<0, 1>(TileShape_MNK{}));
  847. Tensor tScS = threadMma0.partition_C(cS);
  848. #pragma unroll
  849. for (int i = 0; i < size(tSrS); ++i) {
  850. if constexpr (!Is_causal && !Is_local) { // Just masking based on col
  851. if (int(get<1>(tScS(i))) >= int(seqlen_k - n_block * kBlockN)) { tSrS(i) = -INFINITY; }
  852. } else { // mask based on both row and col
  853. int row = int(get<0>(tScS(i))) / kBlockH;
  854. if (int(get<1>(tScS(i))) >= std::min(seqlen_k - n_block * kBlockN, col_limit_right(row, n_block))) {
  855. tSrS(i) = -INFINITY;
  856. } else if constexpr(Is_local) {
  857. if (int(get<1>(tScS(i))) < col_limit_left(row, n_block)) {
  858. tSrS(i) = -INFINITY;
  859. }
  860. }
  861. }
  862. }
  863. }
  864. softmax.template online_softmax</*Is_first=*/true>(tSrS);
  865. Tensor tOrP = make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs_fp8(tSrS.layout()));
  866. permute_regs_A_to_C(tOrP);
  867. Tensor scores_scale = make_fragment_like(softmax.row_max);
  868. clear(scores_scale);
  869. consumer_wait(pipeline_vt, smem_pipe_read);
  870. flash::gemm</*zero_init=*/true, /*wg_wait=*/0>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read.index()), tOrO);
  871. if constexpr(!Delay_V_release) { pipeline_vt.consumer_release(smem_pipe_read); }
  872. ++smem_pipe_read;
  873. --n_block;
  874. constexpr int extra_iterations = !Is_causal ? kStages - 1 : cute::ceil_div(kBlockM_div_H, kBlockN);
  875. if constexpr(Is_causal) {
  876. CUTLASS_PRAGMA_UNROLL
  877. for (int iter = 0; iter < extra_iterations && n_block >= n_block_min; ++iter, --n_block) {
  878. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  879. consumer_wait(pipeline_k, smem_pipe_read);
  880. warp_scheduler_barrier_sync();
  881. flash::gemm</*zero_init=*/true, /*wg_wait=*/0>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read.index()), tSrS);
  882. Tensor cS = cute::make_identity_tensor(select<0, 1>(TileShape_MNK{}));
  883. Tensor tScS = threadMma0.partition_C(cS);
  884. #pragma unroll
  885. for (int i = 0; i < size(tSrS); ++i) {
  886. int row = int(get<0>(tScS(i))) / kBlockH;
  887. if (int(get<1>(tScS(i))) >= col_limit_right(row, n_block)) {
  888. tSrS(i) = -INFINITY;
  889. }
  890. }
  891. warp_scheduler_barrier_arrive();
  892. pipeline_k.consumer_release(smem_pipe_read);
  893. if constexpr(Delay_V_release) {
  894. pipeline_vt.consumer_release(smem_pipe_release);
  895. ++smem_pipe_release;
  896. }
  897. consumer_wait(pipeline_vt, smem_pipe_read);
  898. cute::copy(softmax.template max</*Is_first=*/false, /*Check_inf=*/true>(tSrS), scores_scale);
  899. softmax.rescale_o(tOrO, scores_scale);
  900. softmax.template online_softmax</*Is_first=*/false, /*Check_inf=*/true>(tSrS);
  901. Tensor tOrP = make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs_fp8(tSrS.layout()));
  902. permute_regs_A_to_C(tOrP);
  903. flash::gemm</*zero_init=*/false, /*wg_wait=*/0>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read.index()), tOrO);
  904. if constexpr(!Delay_V_release) { pipeline_vt.consumer_release(smem_pipe_read); }
  905. ++smem_pipe_read;
  906. }
  907. } else if constexpr(!Is_local) {
  908. CUTLASS_PRAGMA_UNROLL
  909. for (int iter = 0; iter < extra_iterations && n_block >= n_block_min; ++iter, --n_block) {
  910. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  911. consumer_wait(pipeline_k, smem_pipe_read);
  912. if constexpr(Delay_V_release) {
  913. pipeline_vt.consumer_release(smem_pipe_release);
  914. ++smem_pipe_release;
  915. }
  916. warp_scheduler_barrier_sync();
  917. flash::gemm</*zero_init=*/true, /*wg_wait=*/0>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read.index()), tSrS);
  918. warp_scheduler_barrier_arrive();
  919. if constexpr(!Delay_V_release) { pipeline_k.consumer_release(smem_pipe_read); }
  920. else { consumer_wait(pipeline_vt, smem_pipe_read); }
  921. cute::copy(softmax.template max</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS), scores_scale);
  922. softmax.rescale_o(tOrO, scores_scale);
  923. softmax.template online_softmax</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS);
  924. Tensor tOrP = make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs_fp8(tSrS.layout()));
  925. permute_regs_A_to_C(tOrP);
  926. if constexpr (Delay_V_release) { pipeline_k.consumer_release(smem_pipe_read); }
  927. else { consumer_wait(pipeline_vt, smem_pipe_read); }
  928. flash::gemm</*zero_init=*/false, /*wg_wait=*/0>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read.index()), tOrO);
  929. if constexpr(!Delay_V_release) { pipeline_vt.consumer_release(smem_pipe_read); }
  930. ++smem_pipe_read;
  931. }
  932. }
  933. if constexpr(Delay_V_release) {
  934. warp_scheduler_barrier_sync();
  935. CUTLASS_PRAGMA_NO_UNROLL
  936. for (; n_block >= n_block_min; --n_block) {
  937. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  938. consumer_wait(pipeline_k, smem_pipe_read);
  939. flash::gemm</*zero_init=*/true, /*wg_wait=*/0>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read.index()), tSrS);
  940. if constexpr(Is_local) {
  941. Tensor cS = cute::make_identity_tensor(select<0, 1>(TileShape_MNK{}));
  942. Tensor tScS = threadMma0.partition_C(cS);
  943. #pragma unroll
  944. for (int i = 0; i < size(tSrS); ++i) {
  945. int row = int(get<0>(tScS(i))) / kBlockH;
  946. if (
  947. int(get<1>(tScS(i))) >= col_limit_right(row, n_block) ||
  948. int(get<1>(tScS(i))) < col_limit_left(row, n_block)
  949. ) {
  950. tSrS(i) = -INFINITY;
  951. }
  952. }
  953. }
  954. warp_scheduler_barrier_arrive();
  955. pipeline_k.consumer_release(smem_pipe_read);
  956. pipeline_vt.consumer_release(smem_pipe_release);
  957. cute::copy(softmax.template max</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS), scores_scale);
  958. softmax.rescale_o(tOrO, scores_scale);
  959. softmax.template online_softmax</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS);
  960. Tensor tOrP = make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs_fp8(tSrS.layout()));
  961. permute_regs_A_to_C(tOrP);
  962. consumer_wait(pipeline_vt, smem_pipe_read);
  963. flash::gemm</*zero_init=*/false, /*wg_wait=*/0>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read.index()), tOrO);
  964. warp_scheduler_barrier_sync();
  965. ++smem_pipe_read;
  966. ++smem_pipe_release;
  967. }
  968. warp_scheduler_barrier_arrive();
  969. pipeline_vt.consumer_release(smem_pipe_release);
  970. ++smem_pipe_release;
  971. } else {
  972. if constexpr (kHeadDim == 128) { warp_scheduler_barrier_sync(); }
  973. CUTLASS_PRAGMA_NO_UNROLL
  974. for (; n_block >= n_block_min; --n_block) {
  975. Tensor tSrS = partition_fragment_C(tiled_mma0, select<0, 1>(TileShape_MNK{}));
  976. consumer_wait(pipeline_k, smem_pipe_read);
  977. if constexpr (kHeadDim == 256) { warp_scheduler_barrier_sync(); }
  978. flash::gemm</*zero_init=*/true, /*wg_wait=*/0>(tiled_mma0, tSrQ, tSrK(_, _, _, smem_pipe_read.index()), tSrS);
  979. if constexpr(Is_local) {
  980. Tensor cS = cute::make_identity_tensor(select<0, 1>(TileShape_MNK{}));
  981. Tensor tScS = threadMma0.partition_C(cS);
  982. #pragma unroll
  983. for (int i = 0; i < size(tSrS); ++i) {
  984. int row = int(get<0>(tScS(i))) / kBlockH;
  985. if (
  986. int(get<1>(tScS(i))) >= col_limit_right(row, n_block) ||
  987. int(get<1>(tScS(i))) < col_limit_left(row, n_block)
  988. ) {
  989. tSrS(i) = -INFINITY;
  990. }
  991. }
  992. }
  993. warp_scheduler_barrier_arrive();
  994. pipeline_k.consumer_release(smem_pipe_read);
  995. cute::copy(softmax.template max</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS), scores_scale);
  996. softmax.rescale_o(tOrO, scores_scale);
  997. softmax.template online_softmax</*Is_first=*/false, /*Check_inf=*/Is_local>(tSrS);
  998. Tensor tOrP = make_tensor(convert_type<Element>(tSrS).data(), convert_layout_acc_Aregs_fp8(tSrS.layout()));
  999. permute_regs_A_to_C(tOrP);
  1000. consumer_wait(pipeline_vt, smem_pipe_read);
  1001. if constexpr (kHeadDim == 128) { warp_scheduler_barrier_sync(); }
  1002. flash::gemm</*zero_init=*/false, /*wg_wait=*/0>(tiled_mma1, tOrP, tOrV(_, _, _, smem_pipe_read.index()), tOrO);
  1003. pipeline_vt.consumer_release(smem_pipe_read);
  1004. ++smem_pipe_read;
  1005. }
  1006. if constexpr (kHeadDim == 128) { warp_scheduler_barrier_arrive(); }
  1007. }
  1008. cutlass::arch::NamedBarrier::arrive(NumMmaThreads + cutlass::NumThreadsPerWarpGroup, static_cast<int>(FwdNamedBarriers::QueryEmpty) /*id*/);
  1009. cute::copy(softmax.template finalize</*Is_dropout=*/false, Is_split>(tSrS, shared_storage.descale_v), scores_scale);
  1010. softmax.rescale_o(tOrO, scores_scale);
  1011. return;
  1012. }
  1013. };
  1014. } // namespace flash