ln_api.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #include <torch/extension.h>
  2. #include "ATen/cuda/CUDAContext.h"
  3. #include "ln.h"
  4. /*
  5. Supported Type combinations:
  6. input residual compute weights output
  7. ============================================
  8. fp32 fp32 fp32 fp32 fp32
  9. fp16 fp32 fp32 fp32 fp16
  10. fp16 fp16 fp32 fp32 fp16
  11. bf16 fp32 fp32 fp32 bf16
  12. bf16 bf16 fp32 fp32 bf16
  13. fp16 fp16 fp32 fp16 fp16
  14. bf16 bf16 fp32 bf16 bf16
  15. Remarks:
  16. Output type = Input type
  17. Compute always in FP32
  18. */
  19. namespace layer_norm {
  20. // Create registries and provide runtime versions of config hash functions.
  21. FwdRegistry FWD_FUNCS;
  22. BwdRegistry BWD_FUNCS;
  23. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24. uint32_t get_type_id(torch::Dtype dtype){
  25. if( dtype == torch::kFloat16 ) {
  26. return TypeId<fp16>::Value;
  27. } else if( dtype == torch::kBFloat16 ) {
  28. return TypeId<bf16>::Value;
  29. } else if( dtype == torch::kFloat32 ) {
  30. return TypeId<fp32>::Value;
  31. } else {
  32. TORCH_CHECK(false, "Type not supported: ", dtype);
  33. }
  34. }
  35. ////////////////////////////////////////////////////////////////////////////////////////////////////
  36. uint64_t get_key(torch::Dtype wtype, torch::Dtype itype, torch::Dtype rtype, torch::Dtype otype, torch::Dtype ctype, uint64_t hidden_size) {
  37. using namespace layer_norm;
  38. uint64_t type_key = get_type_id(wtype) | (get_type_id(itype) << 2) | (get_type_id(rtype) << 4) | (get_type_id(otype) << 6) | (get_type_id(ctype) << 8);
  39. uint64_t launcher_key = (type_key << 32) | hidden_size;
  40. return launcher_key;
  41. }
  42. } // namespace layer_norm
  43. ////////////////////////////////////////////////////////////////////////////////////////////////////
  44. layer_norm::FwdFunction & get_fwd_launcher(torch::Dtype wtype, torch::Dtype itype, torch::Dtype rtype, torch::Dtype otype, torch::Dtype ctype, uint32_t hidden_size) {
  45. auto iter = layer_norm::FWD_FUNCS.find(layer_norm::get_key(wtype, itype, rtype, otype, ctype, hidden_size));
  46. if( iter != layer_norm::FWD_FUNCS.end() ) {
  47. return iter->second;
  48. } else {
  49. TORCH_CHECK(false, "FWD: Unsupported hidden_size or types: ", hidden_size, wtype, itype, rtype, otype, ctype);
  50. }
  51. }
  52. ////////////////////////////////////////////////////////////////////////////////////////////////////
  53. layer_norm::BwdFunction & get_bwd_launcher(torch::Dtype wtype, torch::Dtype itype, torch::Dtype rtype, torch::Dtype otype, torch::Dtype ctype, uint32_t hidden_size) {
  54. auto iter = layer_norm::BWD_FUNCS.find(layer_norm::get_key(wtype, itype, rtype, otype, ctype, hidden_size));
  55. if( iter != layer_norm::BWD_FUNCS.end() ) {
  56. return iter->second;
  57. } else {
  58. TORCH_CHECK(false, "BWD: Unsupported hidden_size or types: ", hidden_size, wtype, itype, rtype, otype, ctype);
  59. }
  60. }
  61. ////////////////////////////////////////////////////////////////////////////////////////////////////
  62. std::vector<at::Tensor> dropout_add_ln_fwd(const at::Tensor &x0, // Input: BxSxhidden_size
  63. c10::optional<const at::Tensor> &x1_, // Residual: BxSxhidden_size
  64. const at::Tensor &gamma, // hidden_size
  65. const at::Tensor &beta, // hidden_size
  66. c10::optional<const at::Tensor> &rowscale_, // BxS
  67. c10::optional<const at::Tensor> &colscale_, // BxS
  68. const float dropout_p,
  69. const float epsilon,
  70. c10::optional<at::Generator> gen_,
  71. bool residual_in_fp32
  72. ) {
  73. auto itype = x0.scalar_type();
  74. auto rtype = x1_.has_value()
  75. ? x1_.value().scalar_type()
  76. : (residual_in_fp32 ? torch::kFloat32 : x0.scalar_type());
  77. auto wtype = gamma.scalar_type();
  78. auto otype = itype;
  79. auto ctype = torch::kFloat32;
  80. auto mtype = torch::kUInt8;
  81. TORCH_CHECK(beta.scalar_type() == wtype);
  82. TORCH_CHECK(x0.is_cuda())
  83. TORCH_CHECK(gamma.is_cuda())
  84. TORCH_CHECK(beta.is_cuda())
  85. TORCH_CHECK(x0.is_contiguous());
  86. auto sizes = x0.sizes();
  87. TORCH_CHECK(sizes.size() == 2);
  88. const int rows = sizes[0];
  89. const int cols = sizes[1];
  90. auto hidden_size = gamma.numel();
  91. if (x1_.has_value()) {
  92. auto x1 = x1_.value();
  93. TORCH_CHECK(x1.is_cuda())
  94. TORCH_CHECK(x1.is_contiguous());
  95. TORCH_CHECK(x1.sizes() == sizes);
  96. }
  97. if (rowscale_.has_value()) {
  98. auto rowscale = rowscale_.value();
  99. TORCH_CHECK(rowscale.is_cuda())
  100. TORCH_CHECK(rowscale.is_contiguous());
  101. TORCH_CHECK(rowscale.sizes() == std::vector<int64_t>{rows});
  102. TORCH_CHECK(rowscale.dtype() == itype);
  103. }
  104. if (colscale_.has_value()) {
  105. auto colscale = colscale_.value();
  106. TORCH_CHECK(colscale.is_cuda())
  107. TORCH_CHECK(colscale.is_contiguous());
  108. TORCH_CHECK(colscale.sizes() == std::vector<int64_t>{cols});
  109. TORCH_CHECK(colscale.dtype() == wtype);
  110. }
  111. TORCH_CHECK(gamma.sizes() == beta.sizes());
  112. TORCH_CHECK(hidden_size == cols);
  113. TORCH_CHECK((hidden_size % 8 == 0) && (hidden_size <= 6144));
  114. TORCH_CHECK(epsilon >= 0.f);
  115. auto opts = x0.options();
  116. bool save_x = x1_.has_value() || (dropout_p > 0.f) || rowscale_.has_value() || colscale_.has_value() || (itype != rtype);
  117. at::Tensor x;
  118. if (save_x) { x = torch::empty(sizes, opts.dtype(rtype)); }
  119. at::Tensor dmask;
  120. if (dropout_p > 0.f) { dmask = torch::empty(sizes, opts.dtype(mtype)); };
  121. auto z = torch::empty(sizes, opts.dtype(otype));
  122. auto mu = torch::empty({ rows }, opts.dtype(ctype));
  123. auto rsigma = torch::empty({ rows }, opts.dtype(ctype));
  124. layer_norm::LaunchParams<layer_norm::FwdParams> launch_params;
  125. launch_params.props = at::cuda::getCurrentDeviceProperties();
  126. launch_params.stream = at::cuda::getCurrentCUDAStream().stream();
  127. TORCH_CHECK(dropout_p < 1.f);
  128. launch_params.params.dropout_keep_p = 1.f - dropout_p;
  129. launch_params.params.x1 = x1_.has_value() ? x1_.value().data_ptr() : nullptr;
  130. launch_params.params.rowscale = rowscale_.has_value() ? rowscale_.value().data_ptr() : nullptr;
  131. launch_params.params.colscale = colscale_.has_value() ? colscale_.value().data_ptr() : nullptr;
  132. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  133. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  134. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  135. const int multiple = hidden_size <= 1536 ? 256 : (hidden_size <= 3072 ? 512 : 1024);
  136. // Request the kernel launcher.
  137. auto launcher = get_fwd_launcher(wtype, itype, rtype, otype, ctype, round_multiple(hidden_size, multiple));
  138. // Query the kernel-specific launch parameters.
  139. launcher(launch_params, true);
  140. at::Tensor workspace, barrier;
  141. // Set the kernel runtime parameters.
  142. layer_norm::FwdParams &params = launch_params.params;
  143. params.rows = rows;
  144. params.cols = cols;
  145. params.x0 = x0.data_ptr();
  146. params.x = save_x ? x.data_ptr() : nullptr;
  147. params.dmask = dropout_p > 0.f ? dmask.data_ptr() : nullptr;
  148. params.mu = mu.data_ptr();
  149. params.rs = rsigma.data_ptr();
  150. params.gamma = gamma.data_ptr();
  151. params.beta = beta.data_ptr();
  152. params.z = z.data_ptr();
  153. params.epsilon = epsilon;
  154. params.dropout_scale = 1.f / (1.f - dropout_p);
  155. params.inverse_cols = 1.f / float(params.cols);
  156. if (dropout_p > 0.f) {
  157. // number of times random will be generated per thread, to offset philox counter in thc random
  158. // state
  159. int64_t counter_offset = launch_params.elts_per_thread;
  160. // See Note [Acquire lock when using random generators]
  161. {
  162. std::lock_guard<std::mutex> lock(gen->mutex_);
  163. params.philox_args = gen->philox_cuda_state(counter_offset);
  164. }
  165. }
  166. if( launch_params.barrier_size > 0 ) {
  167. auto options = x0.options();
  168. barrier = torch::zeros(launch_params.barrier_size, options.dtype(torch::kInt32));
  169. workspace = torch::empty(launch_params.workspace_bytes, options.dtype(torch::kChar));
  170. params.workspace = workspace.data_ptr();
  171. params.barrier = barrier.data_ptr<int>();
  172. }
  173. // Launch the kernel.
  174. launcher(launch_params, false);
  175. return { z, x, dmask, mu, rsigma };
  176. }
  177. ////////////////////////////////////////////////////////////////////////////////////////////////////
  178. std::vector<at::Tensor> dropout_add_ln_bwd(const at::Tensor &dz, // BxSxhidden_size
  179. c10::optional<const at::Tensor> &dx_, // BxSxhidden_size
  180. const at::Tensor &x, // BxSxhidden_size
  181. c10::optional<const at::Tensor> &x0_, // BxSxhidden_size
  182. c10::optional<const at::Tensor> &dmask_, // BxSxhidden_size
  183. const at::Tensor &mu, // BxS, FP32!
  184. const at::Tensor &rsigma, // BxS, FP32!
  185. const at::Tensor &gamma, // hidden_size
  186. c10::optional<const at::Tensor> &rowscale_, // BxS
  187. c10::optional<const at::Tensor> &colscale_, // BxS
  188. const float dropout_p,
  189. const bool has_residual
  190. ) {
  191. auto itype = dz.scalar_type();
  192. auto rtype = x.scalar_type();
  193. auto wtype = gamma.scalar_type();
  194. auto otype = itype;
  195. auto ctype = torch::kFloat32;
  196. auto mtype = torch::kUInt8;
  197. if (dropout_p > 0.f) { TORCH_CHECK(dmask_.has_value()); }
  198. TORCH_CHECK(dz.dtype() == otype);
  199. TORCH_CHECK(mu.dtype() == ctype);
  200. TORCH_CHECK(rsigma.dtype() == ctype);
  201. TORCH_CHECK(x.is_cuda());
  202. TORCH_CHECK(dz.is_cuda());
  203. TORCH_CHECK(mu.is_cuda());
  204. TORCH_CHECK(rsigma.is_cuda());
  205. TORCH_CHECK(gamma.is_cuda());
  206. TORCH_CHECK(x.is_contiguous());
  207. TORCH_CHECK(dz.is_contiguous());
  208. auto sizes = x.sizes();
  209. TORCH_CHECK(sizes.size() == 2);
  210. TORCH_CHECK(dz.sizes() == sizes);
  211. auto rows = sizes[0];
  212. auto cols = sizes[1];
  213. if (dx_.has_value()) {
  214. auto dx = dx_.value();
  215. TORCH_CHECK(dx.dtype() == rtype);
  216. TORCH_CHECK(dx.is_cuda())
  217. TORCH_CHECK(dx.is_contiguous());
  218. TORCH_CHECK(dx.sizes() == sizes);
  219. }
  220. if (dmask_.has_value()) {
  221. auto dmask = dmask_.value();
  222. TORCH_CHECK(dmask.dtype() == mtype);
  223. TORCH_CHECK(dmask.is_cuda());
  224. TORCH_CHECK(dmask.is_contiguous());
  225. TORCH_CHECK(dmask.sizes() == sizes);
  226. }
  227. if (rowscale_.has_value()) {
  228. auto rowscale = rowscale_.value();
  229. TORCH_CHECK(rowscale.is_cuda())
  230. TORCH_CHECK(rowscale.is_contiguous());
  231. TORCH_CHECK(rowscale.sizes() == std::vector<int64_t>{rows});
  232. TORCH_CHECK(rowscale.dtype() == itype);
  233. }
  234. if (colscale_.has_value()) {
  235. auto colscale = colscale_.value();
  236. TORCH_CHECK(colscale.is_cuda())
  237. TORCH_CHECK(colscale.is_contiguous());
  238. TORCH_CHECK(colscale.sizes() == std::vector<int64_t>{cols});
  239. TORCH_CHECK(colscale.dtype() == wtype);
  240. TORCH_CHECK(x0_.has_value());
  241. auto x0 = x0_.value();
  242. TORCH_CHECK(x0.is_cuda())
  243. TORCH_CHECK(x0.is_contiguous());
  244. TORCH_CHECK(x0.sizes() == sizes);
  245. TORCH_CHECK(x0.dtype() == itype);
  246. }
  247. auto hidden_size = gamma.numel();
  248. TORCH_CHECK(hidden_size == cols);
  249. TORCH_CHECK((hidden_size % 8 == 0) && (hidden_size <= 6144));
  250. TORCH_CHECK(mu.numel() == rows);
  251. TORCH_CHECK(mu.sizes() == rsigma.sizes());
  252. TORCH_CHECK(gamma.numel() == cols);
  253. auto opts = x.options();
  254. auto dx0 = torch::empty_like(x, opts.dtype(itype));
  255. at::Tensor dx1;
  256. if (has_residual) { dx1 = torch::empty_like(x, opts.dtype(rtype)); }
  257. auto dgamma = torch::empty_like(gamma);
  258. auto dbeta = torch::empty_like(gamma);
  259. at::Tensor dcolscale;
  260. if (colscale_.has_value()) {
  261. dcolscale = torch::empty_like(colscale_.value());
  262. }
  263. layer_norm::LaunchParams<layer_norm::BwdParams> launch_params;
  264. launch_params.stream = at::cuda::getCurrentCUDAStream().stream();
  265. launch_params.props = at::cuda::getCurrentDeviceProperties();
  266. TORCH_CHECK(dropout_p < 1.f);
  267. launch_params.params.dropout_keep_p = 1.f - dropout_p;
  268. launch_params.params.dx1 = has_residual ? dx1.data_ptr() : nullptr;
  269. launch_params.params.rowscale = rowscale_.has_value() ? rowscale_.value().data_ptr() : nullptr;
  270. launch_params.params.colscale = colscale_.has_value() ? colscale_.value().data_ptr() : nullptr;
  271. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  272. const int multiple = hidden_size <= 1536 ? 256 : (hidden_size <= 3072 ? 512 : 1024);
  273. auto launcher = get_bwd_launcher(wtype, itype, rtype, otype, ctype, round_multiple(hidden_size, multiple));
  274. launcher(launch_params, true);
  275. auto dgamma_part = torch::empty({ launch_params.params.ctas_per_col, hidden_size }, opts.dtype(ctype));
  276. auto dbeta_part = torch::empty({ launch_params.params.ctas_per_col, hidden_size }, opts.dtype(ctype));
  277. at::Tensor dcolscale_part;
  278. if (colscale_.has_value()) {
  279. dcolscale_part = torch::empty({ launch_params.params.ctas_per_col, hidden_size }, opts.dtype(ctype));
  280. }
  281. at::Tensor workspace, barrier;
  282. layer_norm::BwdParams &params = launch_params.params;
  283. params.rows = rows;
  284. params.cols = cols;
  285. params.x = x.data_ptr();
  286. params.x0 = x0_.has_value() ? x0_.value().data_ptr() : nullptr;
  287. params.dmask = dropout_p > 0.f ? dmask_.value().data_ptr() : nullptr;
  288. params.mu = mu.data_ptr();
  289. params.rs = rsigma.data_ptr();
  290. params.gamma = gamma.data_ptr();
  291. params.dz = dz.data_ptr();
  292. params.dx = dx_.has_value() ? dx_.value().data_ptr() : nullptr;
  293. params.dx0 = dx0.data_ptr();
  294. params.dbeta = dbeta.data_ptr();
  295. params.dgamma = dgamma.data_ptr();
  296. params.dcolscale = colscale_.has_value() ? dcolscale.data_ptr() : nullptr;
  297. params.dbeta_part = dbeta_part.data_ptr();
  298. params.dgamma_part = dgamma_part.data_ptr();
  299. params.dcolscale_part = colscale_.has_value() ? dcolscale_part.data_ptr() : nullptr;
  300. params.dropout_scale = 1.f / (1.f - dropout_p);
  301. params.inverse_cols = 1.f / float(params.cols);
  302. if( launch_params.barrier_size > 0 ) {
  303. // TODO Any way to avoid this?
  304. barrier = torch::zeros(launch_params.barrier_size, opts.dtype(torch::kInt32));
  305. workspace = torch::empty(launch_params.workspace_bytes, opts.dtype(torch::kChar));
  306. params.workspace = workspace.data_ptr();
  307. params.barrier = barrier.data_ptr<int>();
  308. }
  309. launcher(launch_params, false);
  310. std::vector<at::Tensor> result = { dx0, dx1, dgamma, dbeta, dgamma_part, dbeta_part };
  311. if (colscale_.has_value()) {
  312. result.push_back(dcolscale);
  313. result.push_back(dcolscale_part);
  314. }
  315. return result;
  316. }
  317. ////////////////////////////////////////////////////////////////////////////////////////////////////
  318. PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  319. m.doc() = "CUDA DropoutAddLayerNorm";
  320. m.def("dropout_add_ln_fwd", &dropout_add_ln_fwd, "Run Dropout + Add + LayerNorm forward kernel");
  321. m.def("dropout_add_ln_bwd", &dropout_add_ln_bwd, "Run Dropout + Add + LayerNorm backward kernel");
  322. }