1
0

flash_bwd_kernel.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /******************************************************************************
  2. * Copyright (c) 2024, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
  3. ******************************************************************************/
  4. #pragma once
  5. #include "cute/tensor.hpp"
  6. #include <cutlass/cutlass.h>
  7. #include <cutlass/arch/reg_reconfig.h>
  8. #include <cutlass/array.h>
  9. #include <cutlass/numeric_types.h>
  10. #include <cutlass/numeric_conversion.h>
  11. #include <cutlass/kernel_hardware_info.h>
  12. #include "cutlass/pipeline/pipeline.hpp"
  13. #include "utils.h"
  14. #include "tile_scheduler_bwd.hpp"
  15. #include "mainloop_bwd_sm90_tma_gmma_ws.hpp"
  16. #include "epilogue_bwd_sm90_tma.hpp"
  17. namespace flash {
  18. using namespace cute;
  19. template <class CollectiveMainloop_, class CollectiveEpilogue_, class TileScheduler_>
  20. class FlashAttnBwd {
  21. public:
  22. // Type Aliases
  23. static constexpr bool Is_causal = CollectiveMainloop_::Is_causal;
  24. static constexpr bool Is_local = CollectiveMainloop_::Is_local;
  25. static_assert(CollectiveMainloop_::Varlen == CollectiveEpilogue_::Varlen);
  26. static constexpr bool Varlen = CollectiveMainloop_::Varlen;
  27. // Mainloop derived types
  28. using CollectiveMainloop = CollectiveMainloop_;
  29. using TileShape_MNK = typename CollectiveMainloop::TileShape_MNK;
  30. using TiledMmaSdP = typename CollectiveMainloop::TiledMmaSdP;
  31. using TiledMmadKV = typename CollectiveMainloop::TiledMmadKV;
  32. using ArchTag = typename CollectiveMainloop::ArchTag;
  33. using ClusterShape = typename CollectiveMainloop::ClusterShape;
  34. using MainloopArguments = typename CollectiveMainloop::Arguments;
  35. using MainloopParams = typename CollectiveMainloop::Params;
  36. static constexpr bool dKV_swapAB = CollectiveMainloop::dKV_swapAB;
  37. // Epilogue derived types
  38. using CollectiveEpilogue = CollectiveEpilogue_;
  39. using EpilogueArguments = typename CollectiveEpilogue::Arguments;
  40. using EpilogueParams = typename CollectiveEpilogue::Params;
  41. static_assert(ArchTag::kMinComputeCapability >= 90);
  42. using TileScheduler = TileScheduler_;
  43. using TileSchedulerArguments = typename TileScheduler::Arguments;
  44. using TileSchedulerParams = typename TileScheduler::Params;
  45. static constexpr uint32_t NumLoadWarpGroups = 1;
  46. static constexpr uint32_t NumMmaWarpGroups = CUTE_STATIC_V(size(TiledMmaSdP{})) / cutlass::NumThreadsPerWarpGroup;
  47. static constexpr uint32_t MaxThreadsPerBlock = CUTE_STATIC_V(size(TiledMmaSdP{})) + (NumLoadWarpGroups * cutlass::NumThreadsPerWarpGroup);
  48. static constexpr uint32_t MinBlocksPerMultiprocessor = 1;
  49. static_assert(NumMmaWarpGroups == 2);
  50. /// Register requirement for Load and Math WGs
  51. static constexpr uint32_t LoadRegisterRequirement = 24;
  52. static constexpr uint32_t MmaRegisterRequirement = 240;
  53. // If you want to print from the producer warp, you'd need to increase the number of registers
  54. // Otherwise you'll get CUDA error.
  55. // static constexpr uint32_t LoadRegisterRequirement = 56;
  56. // static constexpr uint32_t MmaRegisterRequirement = 224;
  57. // Kernel level shared memory storage
  58. struct SharedStorage {
  59. struct {
  60. union {
  61. typename CollectiveMainloop::TensorStorage mainloop;
  62. typename CollectiveEpilogue::TensorStorage epilogue;
  63. };
  64. };
  65. struct {
  66. alignas(16) cutlass::arch::ClusterTransactionBarrier barrier_KV;
  67. alignas(16) cutlass::arch::ClusterBarrier barrier_dKV;
  68. alignas(16) typename CollectiveMainloop::MainloopPipeline::SharedStorage pipeline_q;
  69. alignas(16) typename CollectiveMainloop::MainloopPipeline::SharedStorage pipeline_do;
  70. alignas(16) typename TileScheduler::SharedStorage smem_scheduler;
  71. };
  72. };
  73. static constexpr int SharedStorageSize = sizeof(SharedStorage);
  74. // Device side arguments
  75. struct Arguments {
  76. MainloopArguments mainloop{};
  77. EpilogueArguments epilogue{};
  78. cutlass::KernelHardwareInfo hw_info{};
  79. TileSchedulerArguments scheduler{};
  80. };
  81. // Kernel entry point API
  82. struct Params {
  83. MainloopParams mainloop{};
  84. EpilogueParams epilogue{};
  85. cutlass::KernelHardwareInfo hw_info{};
  86. TileSchedulerParams scheduler{};
  87. };
  88. //
  89. // Methods
  90. //
  91. // Convert to underlying arguments. In this case, a simple copy for the aliased type.
  92. static
  93. Params
  94. to_underlying_arguments(Arguments const& args) {
  95. CUTLASS_TRACE_HOST("to_underlying_arguments():");
  96. // Get SM count if needed, otherwise use user supplied SM count
  97. int sm_count = args.hw_info.sm_count;
  98. if (sm_count <= 0) {
  99. CUTLASS_TRACE_HOST(" WARNING: Arguments do not include a valid SM count.\n"
  100. " For optimal performance, populate the arguments KernelHardwareInfo struct with the SM count.");
  101. sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(args.hw_info.device_id);
  102. }
  103. CUTLASS_TRACE_HOST("to_underlying_arguments(): Setting persistent grid SM count to " << sm_count);
  104. cutlass::KernelHardwareInfo hw_info{args.hw_info.device_id, sm_count};
  105. return {
  106. CollectiveMainloop::to_underlying_arguments(args.mainloop),
  107. CollectiveEpilogue::to_underlying_arguments(args.epilogue),
  108. hw_info,
  109. TileScheduler::to_underlying_arguments(args.scheduler)
  110. };
  111. }
  112. // Computes the kernel launch grid shape based on runtime parameters
  113. static dim3
  114. get_grid_shape(Params const& params) {
  115. return TileScheduler::get_grid_shape(params.scheduler, params.hw_info.sm_count);
  116. }
  117. static dim3
  118. get_block_shape() {
  119. return dim3(MaxThreadsPerBlock, 1, 1);
  120. }
  121. CUTLASS_DEVICE
  122. void
  123. operator()(Params const& params, char* smem_buf) {
  124. static constexpr int NumMmaThreads = NumMmaWarpGroups * cutlass::NumThreadsPerWarpGroup;
  125. static constexpr int NumCopyThreads = NumLoadWarpGroups * cutlass::NumThreadsPerWarpGroup;
  126. static constexpr int kBlockM = get<0>(TileShape_MNK{});
  127. static constexpr int kBlockN = get<1>(TileShape_MNK{});
  128. using MainloopPipeline = typename CollectiveMainloop::MainloopPipeline;
  129. using PipelineParams = typename MainloopPipeline::Params;
  130. using PipelineState = typename MainloopPipeline::PipelineState;
  131. SharedStorage& shared_storage = *reinterpret_cast<SharedStorage*>(smem_buf);
  132. int const lane_predicate = cute::elect_one_sync();
  133. int const warp_idx = cutlass::canonical_warp_idx_sync();
  134. // Issue Tma Descriptor Prefetch from a single thread
  135. if (warp_idx == 0 && lane_predicate) {
  136. CollectiveMainloop::prefetch_tma_descriptors(params.mainloop);
  137. CollectiveEpilogue::prefetch_tma_descriptors(params.epilogue);
  138. }
  139. // Obtain warp index
  140. int const warp_group_thread_idx = threadIdx.x % cutlass::NumThreadsPerWarpGroup;
  141. PipelineParams pipeline_params;
  142. pipeline_params.transaction_bytes = CollectiveMainloop::TmaTransactionBytesQ + CollectiveMainloop::TmaTransactionBytesLSE;
  143. int warp_group_idx = cutlass::canonical_warp_group_idx();
  144. pipeline_params.role = warp_group_idx == 0
  145. ? MainloopPipeline::ThreadCategory::Producer
  146. : MainloopPipeline::ThreadCategory::Consumer;
  147. pipeline_params.is_leader = warp_group_thread_idx == 0;
  148. pipeline_params.num_consumers = NumMmaThreads;
  149. if (warp_idx == 0 && lane_predicate) {
  150. shared_storage.barrier_KV.init(1 /*numThreads*/);
  151. // shared_storage.barrier_dKV.init(size(ClusterShape{}) /*numThreads*/);
  152. }
  153. // We're counting on pipeline_q to call cutlass::arch::fence_barrier_init();
  154. MainloopPipeline pipeline_q(shared_storage.pipeline_q, pipeline_params, ClusterShape{});
  155. MainloopPipeline pipeline_do(shared_storage.pipeline_do, pipeline_params, ClusterShape{});
  156. CollectiveMainloop collective_mainloop;
  157. CollectiveEpilogue collective_epilogue;
  158. // We need this to guarantee that the Pipeline init is visible to all producers and consumer blocks in the Cluster
  159. if constexpr (size(ClusterShape{}) > 1) {
  160. cute::cluster_arrive_relaxed();
  161. cute::cluster_wait();
  162. } else {
  163. __syncthreads();
  164. }
  165. if (warp_group_idx == 0) { // Producer
  166. cutlass::arch::warpgroup_reg_dealloc<LoadRegisterRequirement>();
  167. int warp_idx_in_warpgroup = __shfl_sync(0xffffffff, (threadIdx.x / 32) % 4, 0);
  168. if (warp_idx_in_warpgroup == 0) { // Load K, V, and do TMA on Q and dO
  169. PipelineState smem_pipe_write = cutlass::make_producer_start_state<MainloopPipeline>();
  170. int work_idx = 0;
  171. TileScheduler scheduler(reinterpret_cast<typename TileScheduler::SharedStorage*>(&shared_storage.smem_scheduler));
  172. for (auto work_tile_info = scheduler.template get_initial_work</*IsProducer=*/true>(params.scheduler);
  173. work_tile_info.is_valid(params.scheduler);
  174. work_tile_info = scheduler.template get_next_work</*IsProducer=*/true>(params.scheduler, work_tile_info)) {
  175. auto block_coord = work_tile_info.get_block_coord(params.scheduler);
  176. auto [n_block, bidh, bidb] = block_coord;
  177. if constexpr (Varlen) {
  178. if (n_block * kBlockN >= collective_mainloop.get_seqlen_k(params.mainloop, bidb)) {
  179. scheduler.prefetch_next_work(params.scheduler, work_tile_info);
  180. continue;
  181. }
  182. }
  183. if constexpr (Is_causal || Is_local) {
  184. int const m_block_min = collective_mainloop.get_m_block_min(params.mainloop, n_block, bidb);
  185. int const m_block_max = collective_mainloop.get_m_block_max(params.mainloop, n_block, bidb);
  186. if (m_block_min >= m_block_max) {
  187. scheduler.prefetch_next_work(params.scheduler, work_tile_info);
  188. continue;
  189. }
  190. }
  191. auto scheduler_prefetch = [&scheduler, &params, &work_tile_info]() {
  192. scheduler.prefetch_next_work(params.scheduler, work_tile_info);
  193. };
  194. collective_mainloop.load(params.mainloop, pipeline_q, pipeline_do, smem_pipe_write,
  195. shared_storage, scheduler_prefetch, block_coord, work_idx);
  196. ++work_idx;
  197. }
  198. collective_mainloop.load_tail(pipeline_q, pipeline_do, smem_pipe_write);
  199. } else if (warp_idx_in_warpgroup == 1) {
  200. TileScheduler scheduler(reinterpret_cast<typename TileScheduler::SharedStorage*>(&shared_storage.smem_scheduler));
  201. for (auto work_tile_info = scheduler.template get_initial_work</*IsProducer=*/false>(params.scheduler);
  202. work_tile_info.is_valid(params.scheduler);
  203. work_tile_info = scheduler.template get_next_work</*IsProducer=*/false>(params.scheduler, work_tile_info)) {
  204. auto block_coord = work_tile_info.get_block_coord(params.scheduler);
  205. auto [n_block, bidh, bidb] = block_coord;
  206. if constexpr (Varlen) {
  207. if (n_block * kBlockN >= collective_mainloop.get_seqlen_k(params.mainloop, bidb)) { continue; }
  208. }
  209. if constexpr (Is_causal) {
  210. int const m_block_min = collective_mainloop.get_m_block_min(params.mainloop, n_block, bidb);
  211. int const m_block_max = collective_mainloop.get_m_block_max(params.mainloop, n_block, bidb);
  212. if (m_block_min >= m_block_max) { continue; }
  213. }
  214. collective_mainloop.store_dq(params.mainloop, shared_storage, block_coord);
  215. }
  216. }
  217. } else { // Consumer
  218. cutlass::arch::warpgroup_reg_alloc<MmaRegisterRequirement>();
  219. TileScheduler scheduler(reinterpret_cast<typename TileScheduler::SharedStorage*>(&shared_storage.smem_scheduler));
  220. // Initialize matmul objects.
  221. TiledMmadKV tiled_mma_dKV;
  222. PipelineState smem_pipe_read;
  223. collective_mainloop.mma_init();
  224. scheduler.init_consumer();
  225. int work_idx = 0;
  226. CUTLASS_PRAGMA_NO_UNROLL
  227. for (auto work_tile_info = scheduler.template get_initial_work</*IsProducer=*/false>(params.scheduler);
  228. work_tile_info.is_valid(params.scheduler);
  229. work_tile_info = scheduler.template get_next_work</*IsProducer=*/false>(params.scheduler, work_tile_info)) {
  230. auto block_coord = work_tile_info.get_block_coord(params.scheduler);
  231. auto [n_block, bidh, bidb] = block_coord;
  232. if constexpr (Varlen) {
  233. if (n_block * kBlockN >= collective_mainloop.get_seqlen_k(params.mainloop, bidb)) { continue; }
  234. }
  235. if constexpr (Is_causal || Is_local) {
  236. int const m_block_min = collective_mainloop.get_m_block_min(params.mainloop, n_block, bidb);
  237. int const m_block_max = collective_mainloop.get_m_block_max(params.mainloop, n_block, bidb);
  238. if (m_block_min >= m_block_max) { // We exit early and write 0 to dK and dV
  239. collective_epilogue.store_zero(params.epilogue, threadIdx.x - NumCopyThreads, block_coord);
  240. continue;
  241. }
  242. }
  243. // dK and dV output accumulator.
  244. Tensor tdKrdK = partition_fragment_C(tiled_mma_dKV, select<!dKV_swapAB ? 1 : 2, !dKV_swapAB? 2 : 1>(TileShape_MNK{}));
  245. Tensor tdVrdV = partition_fragment_C(tiled_mma_dKV, select<!dKV_swapAB ? 1 : 2, !dKV_swapAB? 2 : 1>(TileShape_MNK{}));
  246. collective_mainloop.mma(params.mainloop, pipeline_q, pipeline_do, smem_pipe_read,
  247. tdKrdK, tdVrdV, threadIdx.x - NumCopyThreads, work_idx, block_coord, shared_storage);
  248. collective_epilogue.store(params.epilogue, tdKrdK, tdVrdV, shared_storage, tiled_mma_dKV,
  249. threadIdx.x - NumCopyThreads, block_coord);
  250. ++work_idx;
  251. }
  252. collective_epilogue.store_tail();
  253. }
  254. }
  255. };
  256. } // namespace flash