Distributions.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. #pragma once
  3. #include <array>
  4. #include <ATen/native/Math.h>
  5. #include <c10/macros/Macros.h>
  6. #include <c10/util/MathConstants.h>
  7. // ROCm hip compiler doesn't work well with using std:: in kernel functions
  8. #if defined(__CUDA_ARCH__) || defined(__HIPCC__)
  9. #if defined(__CUDA_ARCH__)
  10. #include <c10/cuda/CUDAMathCompat.h>
  11. #elif defined(__HIPCC__)
  12. #include <c10/hip/HIPMathCompat.h>
  13. #endif
  14. #define compat_exp c10::cuda::compat::exp
  15. #define compat_ceil c10::cuda::compat::ceil
  16. #define compat_floor c10::cuda::compat::floor
  17. #define compat_log c10::cuda::compat::log
  18. #define compat_pow c10::cuda::compat::pow
  19. #define compat_sqrt c10::cuda::compat::sqrt
  20. #define compat_tan c10::cuda::compat::tan
  21. #define compat_abs c10::cuda::compat::abs
  22. #define compat_log1p c10::cuda::compat::log1p
  23. #else
  24. #define compat_exp std::exp
  25. #define compat_ceil std::ceil
  26. #define compat_floor std::floor
  27. #define compat_log std::log
  28. #define compat_pow std::pow
  29. #define compat_sqrt std::sqrt
  30. #define compat_tan std::tan
  31. #define compat_abs std::abs
  32. #define compat_log1p std::log1p
  33. #endif
  34. namespace {
  35. #if !defined(__CUDA_ARCH__) && !defined(__HIPCC__)
  36. // we cannot use std::isnan directly due to some incompatibility of
  37. // gcc constexpr'ing and nvcc
  38. using std::isnan;
  39. #endif
  40. // Here sampler_t should be function type scalar_t(void). For gpu
  41. // "sampler" is a device function, but since ROCM doesn't have
  42. // equivalent to nvstd::function, we use a template type parameter to
  43. // capture it.
  44. template<typename scalar_t, typename sampler_t>
  45. struct BaseSampler {
  46. sampler_t sampler;
  47. C10_DEVICE BaseSampler(const sampler_t& sampler): sampler(sampler) {}
  48. C10_DEVICE scalar_t sample() {
  49. return sampler();
  50. }
  51. };
  52. // The function `sample_gamma` is
  53. // is adapted from Numpy's distributions.c implementation.
  54. // It is MIT licensed, so here is the copyright:
  55. /* Copyright 2005 Robert Kern (robert.kern@gmail.com)
  56. *
  57. * Permission is hereby granted, free of charge, to any person obtaining a
  58. * copy of this software and associated documentation files (the
  59. * "Software"), to deal in the Software without restriction, including
  60. * without limitation the rights to use, copy, modify, merge, publish,
  61. * distribute, sublicense, and/or sell copies of the Software, and to
  62. * permit persons to whom the Software is furnished to do so, subject to
  63. * the following conditions:
  64. *
  65. * The above copyright notice and this permission notice shall be included
  66. * in all copies or substantial portions of the Software.
  67. *
  68. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  69. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  70. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  71. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  72. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  73. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  74. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  75. */
  76. template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t, typename normal_sampler_t>
  77. C10_DEVICE scalar_t sample_gamma(scalar_t alpha, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform, BaseSampler<accscalar_t, normal_sampler_t>& standard_normal) {
  78. accscalar_t scale = 1.0f;
  79. // Boost alpha for higher acceptance probability.
  80. if (alpha < 1.0f) {
  81. if (alpha == 0.f) return 0.f;
  82. scale *= compat_pow(1 - standard_uniform.sample(), 1.0f / alpha);
  83. alpha += 1.0f;
  84. }
  85. // This implements the acceptance-rejection method of Marsaglia and Tsang (2000)
  86. // doi:10.1145/358407.358414
  87. const accscalar_t d = alpha - 1.0f / 3.0f;
  88. const accscalar_t c = 1.0f / compat_sqrt(9.0f * d);
  89. for (;;) {
  90. accscalar_t x, y;
  91. do {
  92. x = standard_normal.sample();
  93. y = 1.0f + c * x;
  94. } while (y <= 0);
  95. const accscalar_t v = y * y * y;
  96. const accscalar_t u = 1 - standard_uniform.sample();
  97. const accscalar_t xx = x * x;
  98. if (u < 1.0f - 0.0331f * xx * xx)
  99. return static_cast<scalar_t>(scale * d * v);
  100. if (compat_log(u) < 0.5f * xx + d * (1.0f - v + compat_log(v)))
  101. return static_cast<scalar_t>(scale * d * v);
  102. }
  103. }
  104. /* the functions stirling_approx_tail, binomial_inversion, and btrs are adapted
  105. * from TensorFlow's random_binomial_op.cc implementation. That code is under
  106. * copyright: 2019 The TensorFlow Authors.
  107. *
  108. * It was released under the Apache License, Version 2.0 (the "License"), available at:
  109. * http://www.apache.org/licenses/LICENSE-2.0
  110. */
  111. template<typename scalar_t>
  112. C10_DEVICE scalar_t stirling_approx_tail(scalar_t k) {
  113. constexpr static scalar_t kTailValues[] = {
  114. 0.0810614667953272,
  115. 0.0413406959554092,
  116. 0.0276779256849983,
  117. 0.02079067210376509,
  118. 0.0166446911898211,
  119. 0.0138761288230707,
  120. 0.0118967099458917,
  121. 0.0104112652619720,
  122. 0.00925546218271273,
  123. 0.00833056343336287
  124. };
  125. if (k < std::size(kTailValues)) {
  126. return kTailValues[static_cast<size_t>(k)];
  127. }
  128. scalar_t kp1sq = (k + 1) * (k + 1);
  129. return (1.0 / 12 - (1.0 / 360 - 1.0 / 1260 / kp1sq) / kp1sq) / (k + 1);
  130. }
  131. template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
  132. C10_DEVICE scalar_t binomial_inversion(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
  133. accscalar_t U;
  134. accscalar_t geom_sum = 0;
  135. scalar_t num_geom = 0;
  136. accscalar_t logprob = compat_log1p(-prob);
  137. while (true) {
  138. U = standard_uniform.sample();
  139. accscalar_t geom = compat_ceil(compat_log(U) / logprob);
  140. geom_sum += geom;
  141. if (geom_sum > count) {
  142. break;
  143. }
  144. num_geom = num_geom + 1;
  145. }
  146. return num_geom;
  147. }
  148. template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
  149. C10_DEVICE scalar_t btrs(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
  150. scalar_t k;
  151. accscalar_t U, V, us;
  152. // This is spq in the paper.
  153. const accscalar_t stddev = compat_sqrt(count * prob * (1 - prob));
  154. // Other coefficients for Transformed Rejection sampling.
  155. const accscalar_t b = 1.15 + 2.53 * stddev;
  156. const accscalar_t a = -0.0873 + 0.0248 * b + 0.01 * prob;
  157. const accscalar_t c = count * prob + 0.5;
  158. const accscalar_t v_r = 0.92 - 4.2 / b;
  159. const accscalar_t r = prob / (1 - prob);
  160. const accscalar_t alpha = (2.83 + 5.1 / b) * stddev;
  161. const accscalar_t m = compat_floor((count + 1) * prob);
  162. while (true) {
  163. U = standard_uniform.sample() - 0.5;
  164. V = standard_uniform.sample();
  165. us = 0.5 - compat_abs(U);
  166. k = static_cast<scalar_t>(compat_floor((2 * a / us + b) * U + c));
  167. // Reject non-sensical answers.
  168. if (k < 0 || k > count) {
  169. continue;
  170. }
  171. // Region for which the box is tight, and we can return our calculated value.
  172. // This should happen 0.86 * v_r times. In the limit as n * p is large,
  173. // the acceptance rate converges to ~79% (and in the lower regime it is ~24%).
  174. if (us >= 0.07 && V <= v_r) {
  175. return k;
  176. }
  177. // This deviates from Hormann's BTRS algorithm, as there is a log missing.
  178. // For all (u, v) pairs outside of the bounding box, this calculates the
  179. // transformed-reject ratio.
  180. V = compat_log(V * alpha / (a / (us * us) + b));
  181. accscalar_t upperbound =
  182. ((m + 0.5) * compat_log((m + 1) / (r * (count - m + 1))) +
  183. (count + 1) * compat_log((count - m + 1) / (count - k + 1)) +
  184. (k + 0.5) * compat_log(r * (count - k + 1) / (k + 1)) +
  185. stirling_approx_tail<accscalar_t>(m) + stirling_approx_tail<accscalar_t>(count - m) -
  186. stirling_approx_tail<accscalar_t>(k) - stirling_approx_tail<accscalar_t>(count - k));
  187. if (V <= upperbound) {
  188. return k;
  189. }
  190. }
  191. }
  192. template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
  193. C10_DEVICE scalar_t sample_binomial(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
  194. if (count <= 0.0 || prob <= 0.0) {
  195. return 0;
  196. } else if (prob >= 1.0) {
  197. return count;
  198. } else if (prob <= 0.5) {
  199. if (count * prob >= 10.0) {
  200. // btrs
  201. return btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
  202. } else {
  203. // binomial inversion
  204. return binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
  205. }
  206. } else if (prob > 0.5) {
  207. scalar_t qprob = 1.0 - prob;
  208. if (count * qprob >= 10.0) {
  209. // btrs
  210. return count - btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
  211. } else {
  212. // count - binomial inversion
  213. return count - binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
  214. }
  215. } else {
  216. // prob is nan?
  217. return static_cast<scalar_t>(NAN);
  218. }
  219. }
  220. /*
  221. * This function is derived from the implementation of the digamma function in the Cephes Math Library.
  222. * See note [3-Clause BSD License for the Cephes Math Library] in ATen/native/Math.h.
  223. */
  224. template<typename scalar_t, typename accscalar_t>
  225. C10_DEVICE inline scalar_t digamma_one(scalar_t x) {
  226. constexpr accscalar_t PSI_10 = 2.25175258906672110764;
  227. if (x == 0) {
  228. return INFINITY;
  229. }
  230. accscalar_t additional_summand = 0;
  231. int x_is_integer = x == compat_floor(x);
  232. if (x < 0) {
  233. if (x_is_integer) {
  234. return INFINITY;
  235. }
  236. // it is more standard to write this as recursion, but
  237. // nvcc does not like that
  238. additional_summand = -c10::pi<scalar_t> /
  239. compat_tan(c10::pi<scalar_t> * x);
  240. x = 1 - x;
  241. }
  242. // Push x to be >= 10
  243. accscalar_t result = 0;
  244. while (x < 10) {
  245. result -= 1 / x;
  246. x += 1;
  247. }
  248. if (x == 10) {
  249. return result + PSI_10 + additional_summand;
  250. }
  251. // Compute asymptotic digamma
  252. static const accscalar_t A[] = {
  253. 8.33333333333333333333E-2,
  254. -2.10927960927960927961E-2,
  255. 7.57575757575757575758E-3,
  256. -4.16666666666666666667E-3,
  257. 3.96825396825396825397E-3,
  258. -8.33333333333333333333E-3,
  259. 8.33333333333333333333E-2,
  260. };
  261. accscalar_t y = 0;
  262. if (x < 1.0e17f) {
  263. accscalar_t z = 1.0 / (x * x);
  264. y = z * polevl<accscalar_t>(z, A, 6);
  265. }
  266. return static_cast<scalar_t>(
  267. result + compat_log(x) - (0.5f / x) - y + additional_summand);
  268. }
  269. // Computes the reparameterized gradient -(d/dalpha cdf(x;alpha)) / pdf(x;alpha)
  270. // for random number x drawn from a standard Gamma distribution Gamma(alpha).
  271. template <typename scalar_t, typename accscalar_t>
  272. C10_HOST_DEVICE scalar_t standard_gamma_grad_one(scalar_t alpha_, scalar_t x_) {
  273. // Use a Taylor series expansion for small x.
  274. accscalar_t x = static_cast<accscalar_t>(x_);
  275. accscalar_t alpha = static_cast<accscalar_t>(alpha_);
  276. if (x < 0.8f) {
  277. accscalar_t numer = 1;
  278. accscalar_t denom = alpha;
  279. auto series1 = numer / denom;
  280. auto series2 = numer / (denom * denom);
  281. for (int i = 1; i <= 5; ++i) {
  282. numer *= -x / static_cast<accscalar_t>(i);
  283. denom += 1;
  284. series1 += numer / denom;
  285. series2 += numer / (denom * denom);
  286. }
  287. const auto pow_x_alpha = compat_pow(x, alpha);
  288. const auto gamma_pdf = compat_pow(x, alpha - 1) * compat_exp(-x);
  289. const auto gamma_cdf = pow_x_alpha * series1;
  290. const auto gamma_cdf_alpha =
  291. (compat_log(x) - digamma_one<accscalar_t, accscalar_t>(alpha)) *
  292. gamma_cdf -
  293. pow_x_alpha * series2;
  294. const auto result = -gamma_cdf_alpha / gamma_pdf;
  295. return isnan(result) ? static_cast<scalar_t>( 0.f ) : static_cast<scalar_t>(result);
  296. }
  297. // Use a Rice saddle point expansion for large alpha.
  298. if (alpha > 8.0f) {
  299. if (0.9f * alpha <= x && x <= 1.1f * alpha) {
  300. const auto numer_1 = 1 + 24 * alpha * (1 + 12 * alpha);
  301. const auto numer_2 = 1440 * (alpha * alpha) + 6 * x * (53 - 120 * x)
  302. - 65 * x * x / alpha + alpha * (107 + 3600 * x);
  303. const auto denom = 1244160 * (alpha * alpha) * (alpha * alpha);
  304. return static_cast<scalar_t>(numer_1 * numer_2 / denom);
  305. }
  306. const auto denom = compat_sqrt(8 * alpha);
  307. const auto term2 = denom / (alpha - x);
  308. const auto term3 = compat_pow(
  309. x - alpha - alpha * compat_log(x / alpha),
  310. static_cast<accscalar_t>(-1.5));
  311. const auto term23 = (x < alpha) ? term2 - term3 : term2 + term3;
  312. const auto term1 = compat_log(x / alpha) * term23 -
  313. compat_sqrt(2 / alpha) * (alpha + x) / ((alpha - x) * (alpha - x));
  314. const auto stirling = 1 + 1 / (12 * alpha) * (1 + 1 / (24 * alpha));
  315. const auto numer = x * term1;
  316. return static_cast<scalar_t>(-stirling * numer / denom);
  317. }
  318. // Use a bivariate rational approximation to the reparameterized gradient.
  319. const auto u = compat_log(x / alpha);
  320. const auto v = compat_log(alpha);
  321. static const accscalar_t coef_uv[3][8] = {
  322. {0.16009398, -0.094634809, 0.025146376, -0.0030648343,
  323. 1, 0.32668115, 0.10406089, 0.0014179084},
  324. {0.53487893, 0.1298071, 0.065735949, -0.0015649758,
  325. 0.16639465, 0.020070113, -0.0035938915, -0.00058392623},
  326. {0.040121004, -0.0065914022, -0.0026286047, -0.0013441777,
  327. 0.017050642, -0.0021309326, 0.00085092367, -1.5247877e-07},
  328. };
  329. accscalar_t coef_v[8];
  330. for (int i = 0; i < 8; ++ i) {
  331. coef_v[i] = coef_uv[0][i] + u * (coef_uv[1][i] + u * coef_uv[2][i]);
  332. }
  333. const auto p = coef_v[0] + v * (coef_v[1] + v * (coef_v[2] + v * coef_v[3]));
  334. const auto q = coef_v[4] + v * (coef_v[5] + v * (coef_v[6] + v * coef_v[7]));
  335. return static_cast<scalar_t>(compat_exp(p / q));
  336. }
  337. // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
  338. // Assumes x is close to zero and uses a Taylor expansion.
  339. template <typename scalar_t, typename accscalar_t>
  340. C10_DEVICE inline scalar_t _beta_grad_alpha_small(scalar_t x, scalar_t alpha, scalar_t beta) {
  341. const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha)
  342. - digamma_one<scalar_t, accscalar_t>(alpha + beta) - compat_log(x);
  343. scalar_t numer = 1;
  344. scalar_t series = numer / alpha * (factor + 1 / alpha);
  345. for (int i = 1; i <= 10; ++i) {
  346. scalar_t casted_i = static_cast<scalar_t>(i);
  347. numer *= (casted_i - beta) * x / casted_i;
  348. const scalar_t denom = alpha + casted_i;
  349. series += numer / denom * (factor + 1 / denom);
  350. }
  351. const scalar_t result = x * compat_pow(1 - x, -beta) * series;
  352. return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
  353. }
  354. // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt beta.
  355. // Assumes x is close to zero and uses a Taylor expansion.
  356. template <typename scalar_t, typename accscalar_t>
  357. C10_DEVICE inline scalar_t _beta_grad_beta_small(scalar_t x, scalar_t alpha, scalar_t beta) {
  358. const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha + beta) - digamma_one<scalar_t, accscalar_t>(beta);
  359. scalar_t numer = 1, betas = 1, dbetas = 0, series = factor / alpha;
  360. for (int i = 1; i <= 8; ++i) {
  361. scalar_t casted_i = static_cast<scalar_t>(i);
  362. numer *= -x / casted_i;
  363. dbetas = dbetas * (beta - casted_i) + betas;
  364. betas = betas * (beta - casted_i);
  365. series += numer / (alpha + casted_i) * (dbetas + factor * betas);
  366. }
  367. const scalar_t result = -compat_pow(1 - x, 1 - beta) * series;
  368. return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
  369. }
  370. // Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
  371. // Assumes alpha and beta are both large and uses a Rice saddle point expansion.
  372. // To ensure numerical stability, this computation is performed at higher precision.
  373. template<typename scalar_t, typename accscalar_t>
  374. C10_DEVICE inline scalar_t _beta_grad_alpha_mid(accscalar_t x, accscalar_t alpha, accscalar_t beta) {
  375. const accscalar_t total = alpha + beta;
  376. const accscalar_t mean = alpha / total;
  377. const accscalar_t std = compat_sqrt(alpha * beta / (total + 1)) / total;
  378. if (mean - 0.1 * std <= x && x <= mean + 0.1 * std) {
  379. // Avoid the singularity at x = mean.
  380. const accscalar_t poly = 47 * x * (beta * beta) * (beta * beta) + alpha * (
  381. (43 + 20 * (16 + 27 * beta) * x) * (beta * beta) * beta + alpha * (
  382. 3 * (59 + 180 * beta - 90 * x) * (beta * beta) + alpha * (
  383. (453 + 1620 * beta * (1 - x) - 455 * x) * beta + alpha * (
  384. 8 * (1 - x) * (135 * beta - 11)))));
  385. const accscalar_t prefactor_num = (1 + 12 * alpha) * (1 + 12 * beta) / (total * total);
  386. const accscalar_t prefactor_den = 12960 * alpha * alpha * alpha * beta * beta * (1 + 12 * total);
  387. return prefactor_num / (1 - x) * poly / prefactor_den;
  388. }
  389. const accscalar_t prefactor = -x / compat_sqrt(2 * alpha * beta / total);
  390. const accscalar_t stirling = (1 + 1 / (12 * alpha) + 1 / (288 * alpha * alpha))
  391. * (1 + 1 / (12 * beta) + 1 / (288 * beta * beta))
  392. / (1 + 1 / (12 * total) + 1 / (288 * total * total));
  393. const accscalar_t term1_num = 2 * (alpha * alpha) * (x - 1) + alpha * beta * (x - 1) - x * (beta * beta);
  394. const accscalar_t axbx = alpha * (x - 1) + beta * x;
  395. const accscalar_t term1_den = compat_sqrt(2 * alpha / beta) * compat_pow(total, static_cast<accscalar_t>(1.5f)) * axbx * axbx;
  396. const accscalar_t term1 = term1_num / term1_den;
  397. const accscalar_t term2 = 0.5f * compat_log(alpha / (total * x));
  398. const accscalar_t term3_num = compat_sqrt(8 * alpha * beta / total);
  399. const accscalar_t term3_den = beta * x + alpha * (x - 1);
  400. const accscalar_t term3 = term3_num / term3_den;
  401. const accscalar_t term4_base = beta * compat_log(beta / (total * (1 - x))) +
  402. alpha * compat_log(alpha / (total * x));
  403. const accscalar_t term4 = compat_pow(term4_base, static_cast<accscalar_t>(-1.5f));
  404. const accscalar_t term1234 = term1 + term2 * (term3 + (x < mean ? term4 : -term4));
  405. return static_cast<scalar_t>(stirling * prefactor * term1234);
  406. }
  407. // Computes a scaled reparameterized gradient
  408. // -(d/dalpha cdf(x;alpha,beta)) / pdf(x;alpha,beta) / (1-x)
  409. // for random number x drawn from a Beta distribution Beta(alpha,beta).
  410. // This function inputs total=alpha+beta to make it easy to implement
  411. // Dirichlet reparameterized gradients in terms of Betas.
  412. template<typename scalar_t, typename accscalar_t>
  413. C10_HOST_DEVICE inline scalar_t dirichlet_grad_one(scalar_t x, scalar_t alpha, scalar_t total) {
  414. accscalar_t x_ = static_cast<accscalar_t>(x);
  415. accscalar_t alpha_ = static_cast<accscalar_t>(alpha);
  416. accscalar_t total_ = static_cast<accscalar_t>(total);
  417. const scalar_t beta = total - alpha;
  418. const accscalar_t beta_ = total_ - alpha_;
  419. const scalar_t boundary = total * x * (1 - x);
  420. // Use an asymptotic approximation for x close to 0.
  421. if (x <= 0.5f && boundary < 2.5f) {
  422. return _beta_grad_alpha_small<scalar_t, accscalar_t>(x, alpha, beta);
  423. }
  424. // Use an asymptotic approximation for x close to 1.
  425. if (x >= 0.5f && boundary < 0.75f) {
  426. return -_beta_grad_beta_small<scalar_t, accscalar_t>(1 - x, beta, alpha);
  427. }
  428. // Use an asymptotic approximation when alpha and (total - alpha) are both large.
  429. if (alpha > 6 && beta > 6) {
  430. return _beta_grad_alpha_mid<scalar_t, accscalar_t>(x_, alpha_, beta_);
  431. }
  432. // Use a rational correction to an analytic approximation.
  433. static const accscalar_t c[2][3][3][4] = {
  434. {{{1.003668233, -0.01061107488, -0.0657888334, 0.01201642863},
  435. {0.6336835991, -0.3557432599, 0.05486251648, -0.001465281033},
  436. {-0.03276231906, 0.004474107445, 0.002429354597, -0.0001557569013}},
  437. {{0.221950385, -0.3187676331, 0.01799915743, 0.01074823814},
  438. {-0.2951249643, 0.06219954479, 0.01535556598, 0.001550077057},
  439. {0.02155310298, 0.004170831599, 0.001292462449, 6.976601077e-05}},
  440. {{-0.05980841433, 0.008441916499, 0.01085618172, 0.002319392565},
  441. {0.02911413504, 0.01400243777, -0.002721828457, 0.000751041181},
  442. {0.005900514878, -0.001936558688, -9.495446725e-06, 5.385558597e-05}}},
  443. {{{1, -0.02924021934, -0.04438342661, 0.007285809825},
  444. {0.6357567472, -0.3473456711, 0.05454656494, -0.002407477521},
  445. {-0.03301322327, 0.004845219414, 0.00231480583, -0.0002307248149}},
  446. {{0.5925320577, -0.1757678135, 0.01505928619, 0.000564515273},
  447. {0.1014815858, -0.06589186703, 0.01272886114, -0.0007316646956},
  448. {-0.007258481865, 0.001096195486, 0.0003934994223, -4.12701925e-05}},
  449. {{0.06469649321, -0.0236701437, 0.002902096474, -5.896963079e-05},
  450. {0.001925008108, -0.002869809258, 0.0008000589141, -6.063713228e-05},
  451. {-0.0003477407336, 6.959756487e-05, 1.097287507e-05, -1.650964693e-06}}},
  452. };
  453. const accscalar_t u = compat_log(x_);
  454. const accscalar_t a = compat_log(alpha_) - u;
  455. const accscalar_t b = compat_log(total_) - a;
  456. const accscalar_t pow_u[3] = {1, u, u * u};
  457. const accscalar_t pow_a[3] = {1, a, a * a};
  458. accscalar_t p = 0.0;
  459. accscalar_t q = 0.0;
  460. for (int i = 0; i < 3; ++i) {
  461. for (int j = 0; j < 3; ++j) {
  462. const accscalar_t ua = pow_u[i] * pow_a[j];
  463. p += ua * (c[0][i][j][0] + b * (c[0][i][j][1] + b * (c[0][i][j][2] + b * c[0][i][j][3])));
  464. q += ua * (c[1][i][j][0] + b * (c[1][i][j][1] + b * (c[1][i][j][2] + b * c[1][i][j][3])));
  465. }
  466. }
  467. const accscalar_t approx = x_ * (digamma_one<scalar_t, accscalar_t>(total_) - digamma_one<scalar_t, accscalar_t>(alpha_)) / beta_;
  468. return static_cast<scalar_t>(p / q * approx);
  469. }
  470. } // namespace
  471. #else
  472. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  473. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)