ln_api.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. const float dropout_p,
  68. const float epsilon,
  69. c10::optional<at::Generator> gen_,
  70. bool residual_in_fp32
  71. ) {
  72. auto itype = x0.scalar_type();
  73. auto rtype = x1_.has_value()
  74. ? x1_.value().scalar_type()
  75. : (residual_in_fp32 ? torch::kFloat32 : x0.scalar_type());
  76. auto wtype = gamma.scalar_type();
  77. auto otype = itype;
  78. auto ctype = torch::kFloat32;
  79. auto mtype = torch::kUInt8;
  80. TORCH_CHECK(beta.scalar_type() == wtype);
  81. TORCH_CHECK(x0.is_cuda())
  82. TORCH_CHECK(gamma.is_cuda())
  83. TORCH_CHECK(beta.is_cuda())
  84. TORCH_CHECK(x0.is_contiguous());
  85. auto sizes = x0.sizes();
  86. TORCH_CHECK(sizes.size() == 2);
  87. const int rows = sizes[0];
  88. const int cols = sizes[1];
  89. auto hidden_size = gamma.numel();
  90. if (x1_.has_value()) {
  91. auto x1 = x1_.value();
  92. TORCH_CHECK(x1.is_cuda())
  93. TORCH_CHECK(x1.is_contiguous());
  94. TORCH_CHECK(x1.sizes() == sizes);
  95. }
  96. if (rowscale_.has_value()) {
  97. auto rowscale = rowscale_.value();
  98. TORCH_CHECK(rowscale.is_cuda())
  99. TORCH_CHECK(rowscale.is_contiguous());
  100. TORCH_CHECK(rowscale.sizes() == std::vector<int64_t>{rows});
  101. TORCH_CHECK(rowscale.scalar_type() == itype);
  102. }
  103. TORCH_CHECK(gamma.sizes() == beta.sizes());
  104. TORCH_CHECK(hidden_size == cols);
  105. TORCH_CHECK((hidden_size % 8 == 0) && (hidden_size <= 6144));
  106. TORCH_CHECK(epsilon >= 0.f);
  107. auto opts = x0.options();
  108. bool save_x = x1_.has_value() || (dropout_p > 0.f) || (itype != rtype);
  109. at::Tensor x;
  110. if (save_x) { x = torch::empty(sizes, opts.dtype(rtype)); }
  111. at::Tensor dmask;
  112. if (dropout_p > 0.f) { dmask = torch::empty(sizes, opts.dtype(mtype)); };
  113. auto z = torch::empty(sizes, opts.dtype(otype));
  114. auto mu = torch::empty({ rows }, opts.dtype(ctype));
  115. auto rsigma = torch::empty({ rows }, opts.dtype(ctype));
  116. layer_norm::LaunchParams<layer_norm::FwdParams> launch_params;
  117. launch_params.props = at::cuda::getCurrentDeviceProperties();
  118. launch_params.stream = at::cuda::getCurrentCUDAStream().stream();
  119. TORCH_CHECK(dropout_p < 1.f);
  120. launch_params.params.dropout_keep_p = 1.f - dropout_p;
  121. launch_params.params.x1 = x1_.has_value() ? x1_.value().data_ptr() : nullptr;
  122. launch_params.params.rowscale = rowscale_.has_value() ? rowscale_.value().data_ptr() : nullptr;
  123. auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
  124. gen_, at::cuda::detail::getDefaultCUDAGenerator());
  125. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  126. const int multiple = hidden_size <= 1536 ? 256 : (hidden_size <= 3072 ? 512 : 1024);
  127. // Request the kernel launcher.
  128. auto launcher = get_fwd_launcher(wtype, itype, rtype, otype, ctype, round_multiple(hidden_size, multiple));
  129. // Query the kernel-specific launch parameters.
  130. launcher(launch_params, true);
  131. at::Tensor workspace, barrier;
  132. // Set the kernel runtime parameters.
  133. layer_norm::FwdParams &params = launch_params.params;
  134. params.rows = rows;
  135. params.cols = cols;
  136. params.x0 = x0.data_ptr();
  137. params.x = save_x ? x.data_ptr() : nullptr;
  138. params.dmask = dropout_p > 0.f ? dmask.data_ptr() : nullptr;
  139. params.mu = mu.data_ptr();
  140. params.rs = rsigma.data_ptr();
  141. params.gamma = gamma.data_ptr();
  142. params.beta = beta.data_ptr();
  143. params.z = z.data_ptr();
  144. params.epsilon = epsilon;
  145. params.dropout_scale = 1.f / (1.f - dropout_p);
  146. params.inverse_cols = 1.f / float(params.cols);
  147. if (dropout_p > 0.f) {
  148. // number of times random will be generated per thread, to offset philox counter in thc random
  149. // state
  150. int64_t counter_offset = launch_params.elts_per_thread;
  151. // See Note [Acquire lock when using random generators]
  152. {
  153. std::lock_guard<std::mutex> lock(gen->mutex_);
  154. params.philox_args = gen->philox_cuda_state(counter_offset);
  155. }
  156. }
  157. if( launch_params.barrier_size > 0 ) {
  158. auto options = x0.options();
  159. barrier = torch::zeros(launch_params.barrier_size, options.dtype(torch::kInt32));
  160. workspace = torch::empty(launch_params.workspace_bytes, options.dtype(torch::kChar));
  161. params.workspace = workspace.data_ptr();
  162. params.barrier = barrier.data_ptr<int>();
  163. }
  164. // Launch the kernel.
  165. launcher(launch_params, false);
  166. return { z, x, dmask, mu, rsigma };
  167. }
  168. ////////////////////////////////////////////////////////////////////////////////////////////////////
  169. std::vector<at::Tensor> dropout_add_ln_bwd(const at::Tensor &dz, // BxSxhidden_size
  170. const at::Tensor &x, // BxSxhidden_size
  171. c10::optional<const at::Tensor> &dmask_, // BxSxhidden_size
  172. const at::Tensor &mu, // BxS, FP32!
  173. const at::Tensor &rsigma, // BxS, FP32!
  174. const at::Tensor &gamma, // hidden_size
  175. c10::optional<const at::Tensor> &rowscale_, // BxS
  176. const float dropout_p,
  177. const bool has_residual
  178. ) {
  179. auto itype = dz.scalar_type();
  180. auto rtype = x.scalar_type();
  181. auto wtype = gamma.scalar_type();
  182. auto otype = itype;
  183. auto ctype = torch::kFloat32;
  184. auto mtype = torch::kUInt8;
  185. if (dropout_p > 0.f) { TORCH_CHECK(dmask_.has_value()); }
  186. TORCH_CHECK(dz.dtype() == otype);
  187. TORCH_CHECK(mu.dtype() == ctype);
  188. TORCH_CHECK(rsigma.dtype() == ctype);
  189. TORCH_CHECK(x.is_cuda());
  190. TORCH_CHECK(dz.is_cuda());
  191. TORCH_CHECK(mu.is_cuda());
  192. TORCH_CHECK(rsigma.is_cuda());
  193. TORCH_CHECK(gamma.is_cuda());
  194. TORCH_CHECK(x.is_contiguous());
  195. TORCH_CHECK(dz.is_contiguous());
  196. auto sizes = x.sizes();
  197. TORCH_CHECK(sizes.size() == 2);
  198. TORCH_CHECK(dz.sizes() == sizes);
  199. auto rows = sizes[0];
  200. auto cols = sizes[1];
  201. if (dmask_.has_value()) {
  202. auto dmask = dmask_.value();
  203. TORCH_CHECK(dmask.dtype() == mtype);
  204. TORCH_CHECK(dmask.is_cuda());
  205. TORCH_CHECK(dmask.is_contiguous());
  206. TORCH_CHECK(dmask.sizes() == sizes);
  207. }
  208. if (rowscale_.has_value()) {
  209. auto rowscale = rowscale_.value();
  210. TORCH_CHECK(rowscale.is_cuda())
  211. TORCH_CHECK(rowscale.is_contiguous());
  212. TORCH_CHECK(rowscale.sizes() == std::vector<int64_t>{rows});
  213. TORCH_CHECK(rowscale.scalar_type() == itype);
  214. }
  215. auto hidden_size = gamma.numel();
  216. TORCH_CHECK(hidden_size == cols);
  217. TORCH_CHECK((hidden_size % 8 == 0) && (hidden_size <= 6144));
  218. TORCH_CHECK(mu.numel() == rows);
  219. TORCH_CHECK(mu.sizes() == rsigma.sizes());
  220. TORCH_CHECK(gamma.numel() == cols);
  221. auto opts = x.options();
  222. auto dx0 = torch::empty_like(x, opts.dtype(itype));
  223. at::Tensor dx1;
  224. if (has_residual) { dx1 = torch::empty_like(x, opts.dtype(rtype)); }
  225. auto dgamma = torch::empty_like(gamma);
  226. auto dbeta = torch::empty_like(gamma);
  227. layer_norm::LaunchParams<layer_norm::BwdParams> launch_params;
  228. launch_params.stream = at::cuda::getCurrentCUDAStream().stream();
  229. launch_params.props = at::cuda::getCurrentDeviceProperties();
  230. TORCH_CHECK(dropout_p < 1.f);
  231. launch_params.params.dropout_keep_p = 1.f - dropout_p;
  232. launch_params.params.dx1 = has_residual ? dx1.data_ptr() : nullptr;
  233. launch_params.params.rowscale = rowscale_.has_value() ? rowscale_.value().data_ptr() : nullptr;
  234. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  235. const int multiple = hidden_size <= 1536 ? 256 : (hidden_size <= 3072 ? 512 : 1024);
  236. auto launcher = get_bwd_launcher(wtype, itype, rtype, otype, ctype, round_multiple(hidden_size, multiple));
  237. launcher(launch_params, true, /*prenorm=*/false);
  238. auto dgamma_part = torch::empty({ launch_params.params.ctas_per_col, hidden_size }, opts.dtype(ctype));
  239. auto dbeta_part = torch::empty({ launch_params.params.ctas_per_col, hidden_size }, opts.dtype(ctype));
  240. at::Tensor workspace, barrier;
  241. layer_norm::BwdParams &params = launch_params.params;
  242. params.rows = rows;
  243. params.cols = cols;
  244. params.x = x.data_ptr();
  245. params.dmask = dropout_p > 0.f ? dmask_.value().data_ptr() : nullptr;
  246. params.mu = mu.data_ptr();
  247. params.rs = rsigma.data_ptr();
  248. params.gamma = gamma.data_ptr();
  249. params.dz = dz.data_ptr();
  250. params.dx0 = dx0.data_ptr();
  251. params.dbeta = dbeta.data_ptr();
  252. params.dgamma = dgamma.data_ptr();
  253. params.dbeta_part = dbeta_part.data_ptr();
  254. params.dgamma_part = dgamma_part.data_ptr();
  255. params.dropout_scale = 1.f / (1.f - dropout_p);
  256. params.inverse_cols = 1.f / float(params.cols);
  257. if( launch_params.barrier_size > 0 ) {
  258. // TODO Any way to avoid this?
  259. barrier = torch::zeros(launch_params.barrier_size, opts.dtype(torch::kInt32));
  260. workspace = torch::empty(launch_params.workspace_bytes, opts.dtype(torch::kChar));
  261. params.workspace = workspace.data_ptr();
  262. params.barrier = barrier.data_ptr<int>();
  263. }
  264. launcher(launch_params, false, /*prenorm=*/false);
  265. return { dx0, dx1, dgamma, dbeta, dgamma_part, dbeta_part };
  266. }
  267. ////////////////////////////////////////////////////////////////////////////////////////////////////
  268. std::vector<at::Tensor> dropout_add_ln_prenorm_bwd(const at::Tensor &dz, // BxSxhidden_size
  269. const at::Tensor &dx, // BxSxhidden_size
  270. const at::Tensor &x, // BxSxhidden_size
  271. c10::optional<const at::Tensor> &dmask_, // BxSxhidden_size
  272. const at::Tensor &mu, // BxS, FP32!
  273. const at::Tensor &rsigma, // BxS, FP32!
  274. const at::Tensor &gamma, // hidden_size
  275. c10::optional<const at::Tensor> &rowscale_, // BxS
  276. const float dropout_p,
  277. const bool has_residual
  278. ) {
  279. auto itype = dz.scalar_type();
  280. auto rtype = x.scalar_type();
  281. auto wtype = gamma.scalar_type();
  282. auto otype = itype;
  283. auto ctype = torch::kFloat32;
  284. auto mtype = torch::kUInt8;
  285. if (dropout_p > 0.f) { TORCH_CHECK(dmask_.has_value()); }
  286. TORCH_CHECK(dz.dtype() == otype);
  287. TORCH_CHECK(dx.dtype() == rtype);
  288. TORCH_CHECK(mu.dtype() == ctype);
  289. TORCH_CHECK(rsigma.dtype() == ctype);
  290. TORCH_CHECK(x.is_cuda());
  291. TORCH_CHECK(dz.is_cuda());
  292. TORCH_CHECK(dx.is_cuda());
  293. TORCH_CHECK(mu.is_cuda());
  294. TORCH_CHECK(rsigma.is_cuda());
  295. TORCH_CHECK(gamma.is_cuda());
  296. TORCH_CHECK(x.is_contiguous());
  297. TORCH_CHECK(dz.is_contiguous());
  298. TORCH_CHECK(dx.is_contiguous());
  299. auto sizes = x.sizes();
  300. TORCH_CHECK(sizes.size() == 2);
  301. TORCH_CHECK(dz.sizes() == sizes);
  302. TORCH_CHECK(dx.sizes() == sizes);
  303. auto rows = sizes[0];
  304. auto cols = sizes[1];
  305. if (dmask_.has_value()) {
  306. auto dmask = dmask_.value();
  307. TORCH_CHECK(dmask.dtype() == mtype);
  308. TORCH_CHECK(dmask.is_cuda());
  309. TORCH_CHECK(dmask.is_contiguous());
  310. TORCH_CHECK(dmask.sizes() == sizes);
  311. }
  312. if (rowscale_.has_value()) {
  313. auto rowscale = rowscale_.value();
  314. TORCH_CHECK(rowscale.is_cuda())
  315. TORCH_CHECK(rowscale.is_contiguous());
  316. TORCH_CHECK(rowscale.sizes() == std::vector<int64_t>{rows});
  317. TORCH_CHECK(rowscale.scalar_type() == itype);
  318. }
  319. auto hidden_size = gamma.numel();
  320. TORCH_CHECK(hidden_size == cols);
  321. TORCH_CHECK((hidden_size % 8 == 0) && (hidden_size <= 6144));
  322. TORCH_CHECK(mu.numel() == rows);
  323. TORCH_CHECK(mu.sizes() == rsigma.sizes());
  324. TORCH_CHECK(gamma.numel() == cols);
  325. auto opts = x.options();
  326. auto dx0 = torch::empty_like(x, opts.dtype(itype));
  327. at::Tensor dx1;
  328. if (has_residual) { dx1 = torch::empty_like(x, opts.dtype(rtype)); }
  329. auto dgamma = torch::empty_like(gamma);
  330. auto dbeta = torch::empty_like(gamma);
  331. layer_norm::LaunchParams<layer_norm::BwdParams> launch_params;
  332. launch_params.stream = at::cuda::getCurrentCUDAStream().stream();
  333. launch_params.props = at::cuda::getCurrentDeviceProperties();
  334. TORCH_CHECK(dropout_p < 1.f);
  335. launch_params.params.dropout_keep_p = 1.f - dropout_p;
  336. launch_params.params.dx1 = has_residual ? dx1.data_ptr() : nullptr;
  337. launch_params.params.rowscale = rowscale_.has_value() ? rowscale_.value().data_ptr() : nullptr;
  338. auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  339. const int multiple = hidden_size <= 1536 ? 256 : (hidden_size <= 3072 ? 512 : 1024);
  340. auto launcher = get_bwd_launcher(wtype, itype, rtype, otype, ctype, round_multiple(hidden_size, multiple));
  341. launcher(launch_params, true, /*prenorm=*/true);
  342. auto dgamma_part = torch::empty({ launch_params.params.ctas_per_col, hidden_size }, opts.dtype(ctype));
  343. auto dbeta_part = torch::empty({ launch_params.params.ctas_per_col, hidden_size }, opts.dtype(ctype));
  344. at::Tensor workspace, barrier;
  345. layer_norm::BwdParams &params = launch_params.params;
  346. params.rows = rows;
  347. params.cols = cols;
  348. params.x = x.data_ptr();
  349. params.dmask = dropout_p > 0.f ? dmask_.value().data_ptr() : nullptr;
  350. params.mu = mu.data_ptr();
  351. params.rs = rsigma.data_ptr();
  352. params.gamma = gamma.data_ptr();
  353. params.dz = dz.data_ptr();
  354. params.dx = dx.data_ptr();
  355. params.dx0 = dx0.data_ptr();
  356. params.dbeta = dbeta.data_ptr();
  357. params.dgamma = dgamma.data_ptr();
  358. params.dbeta_part = dbeta_part.data_ptr();
  359. params.dgamma_part = dgamma_part.data_ptr();
  360. params.dropout_scale = 1.f / (1.f - dropout_p);
  361. params.inverse_cols = 1.f / float(params.cols);
  362. if( launch_params.barrier_size > 0 ) {
  363. // TODO Any way to avoid this?
  364. barrier = torch::zeros(launch_params.barrier_size, opts.dtype(torch::kInt32));
  365. workspace = torch::empty(launch_params.workspace_bytes, opts.dtype(torch::kChar));
  366. params.workspace = workspace.data_ptr();
  367. params.barrier = barrier.data_ptr<int>();
  368. }
  369. launcher(launch_params, false, /*prenorm=*/true);
  370. return { dx0, dx1, dgamma, dbeta, dgamma_part, dbeta_part };
  371. }
  372. ////////////////////////////////////////////////////////////////////////////////////////////////////
  373. PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  374. m.doc() = "CUDA DropoutAddLayerNorm";
  375. m.def("dropout_add_ln_fwd", &dropout_add_ln_fwd, "Run Dropout + Add + LayerNorm forward kernel");
  376. m.def("dropout_add_ln_bwd", &dropout_add_ln_bwd, "Run Dropout + Add + LayerNorm backward kernel");
  377. m.def("dropout_add_ln_prenorm_bwd", &dropout_add_ln_prenorm_bwd, "Run Dropout + Add + LayerNorm (PreNorm version) backward kernel");
  378. }