Repository navigation
Conversation
|
I'll be away for the next two weeks, but made this PR to avoid duplicated work |
|
The improved |
…pass Add stan/math/rev/fun/grad_reg_inc_beta.hpp. For var arguments the values are computed in double by the prim overload, and the reverse pass computes the a and b adjoints directly as H v (H the Hessian of I_z(a, b) in (a, b)) from the power series or continued fraction, instead of taping through the loop. The z adjoint is closed form. One-sided requests compute only H_aa or H_bb unless the cross term is needed. Also: - simplify the prim grad_reg_inc_beta kernels: one Lentz step for even and odd terms, log-derivatives carried through the steps, the sign folded into the prefactor - rewrite rev and fwd inc_beta with make_callback_var / if constexpr; fvar and var mixes are not supported - move the beta, beta_proportion, neg_binomial and student_t cdfs to the GRAD_RIB interfaces, computing digamma inside the loops instead of with VectorBuilder - fix neg_binomial_cdf (missing return, P / P_i, size_zero, &&) - vectorized inc_beta_dda and inc_beta_ddz, with tests - remove the TensorFlow Probability license file
|
@SteveBronder, excellent additional speedup. My measurements
|
I pushed a34e6f7. It calls
The second commit, 3fd3fe2, starts the new mix test from an empty autodiff stack, because the With these two commits, the generated One behavior stays as before: with a zero tangent on |
|
@avehtari can you split this one up as well? Given the amount of code changed, might be better to land this in parts. The |
|
@andrjohns how many PRs would you prefer? There are 3 logical parts and thus it would be possible to split this in 3 PRs
B2 and B3 are independent of each other. B3 is is big in lines, but it's the same edit in each file. Instead of 3 PRs, there could be 2 by having B1 and B2 in one PR. Or there could be 5 PRs by splitting B3 by family. Let me know what you prefer, and I'll do the split |
Jenkins Console Log Machine informationDistributor ID: Ubuntu Description: Ubuntu 20.04.3 LTS Release: 20.04 Codename: focal CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian Address sizes: 52 bits physical, 57 bits virtual CPU(s): 192 On-line CPU(s) list: 0-191 Thread(s) per core: 2 Core(s) per socket: 48 Socket(s): 2 NUMA node(s): 2 Vendor ID: AuthenticAMD CPU family: 25 Model: 17 Model name: AMD EPYC 9474F 48-Core Processor Stepping: 1 Frequency boost: enabled CPU MHz: 1497.134 CPU max MHz: 4114.4229 CPU min MHz: 1500.0000 BogoMIPS: 7189.39 Virtualization: AMD-V L1d cache: 3 MiB L1i cache: 3 MiB L2 cache: 96 MiB L3 cache: 512 MiB NUMA node0 CPU(s): 0-47,96-143 NUMA node1 CPU(s): 48-95,144-191 Vulnerability Gather data sampling: Not affected Vulnerability Indirect target selection: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Old microcode: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Mitigation; Safe RET Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; PBRSB-eIBRS Not affected; BHI Not affected Vulnerability Srbds: Not affected Vulnerability Tsa: Mitigation; Clear CPU buffers Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Mitigation; IBPB before exit to userspace Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap G++: g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Clang: clang version 10.0.0-4ubuntu1 Target: x86_64-pc-linux-gnu Thread model: posix InstalledDir: /usr/bin |
|
@andrjohns sorry I made this PR a lot longer as I started fixing things adjacent / related to this PR. Some of this code has not been updated in years so I figured while we are here I would fix up nearby places With my fixes as well a lot of cdfs are now 10x faster than they were before. I've read over all of Aki's code and can handle the rest of the review if you are okay with that
|
Multi-line comments in the prim and rev grad_reg_inc_beta kernels and in the new tests are now part of the doc comments, and the docs are rewritten to read in order: the expansion, its derivatives, how the code evaluates them, and when the loop stops. The swap of requested partials and the track_b flag are now written inline, the overloads dispatch with require_all_not_var_t / require_any_var_t, and the continued-fraction stop test is fixed to compile after inlining.
Jenkins Console Log Machine informationDistributor ID: Ubuntu Description: Ubuntu 20.04.3 LTS Release: 20.04 Codename: focal CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian Address sizes: 46 bits physical, 48 bits virtual CPU(s): 80 On-line CPU(s) list: 0-79 Thread(s) per core: 2 Core(s) per socket: 20 Socket(s): 2 NUMA node(s): 2 Vendor ID: GenuineIntel CPU family: 6 Model: 85 Model name: Intel(R) Xeon(R) Gold 6248 CPU @ 2.50GHz Stepping: 7 CPU MHz: 1001.187 CPU max MHz: 3900.0000 CPU min MHz: 1000.0000 BogoMIPS: 5000.00 Virtualization: VT-x L1d cache: 1.3 MiB L1i cache: 1.3 MiB L2 cache: 40 MiB L3 cache: 55 MiB NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78 NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks Vulnerability Itlb multihit: KVM: Mitigation: Split huge pages Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Old microcode: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Mitigation; Enhanced IBRS Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Mitigation; TSX disabled Vulnerability Vmscape: Mitigation; IBPB before exit to userspace Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi pku ospke avx512_vnni md_clear flush_l1d arch_capabilities G++: g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Clang: clang version 10.0.0-4ubuntu1 Target: x86_64-pc-linux-gnu Thread model: posix InstalledDir: /usr/bin |
|
No worries both! I think it would be good to split at least the B1 row from Aki's table to a separate PR, since those are the big algorithmic changes |

Replace the incomplete beta gradient roots with a continued-fraction implementation from TensorFlow Probability
Big increase in stability, accuracy and speed.
Fixes #2417.
This PR was Claude assisted
Summary
grad_reg_inc_beta,inc_beta_ddaandinc_beta_ddbcompute the derivatives of the regularized incomplete beta functionI_z(a, b)with respect to the shapesaandb.develophas two separate implementations of these derivatives. Path A (inc_beta_dda,inc_beta_ddb) servesbeta_cdf,neg_binomial_cdfandneg_binomial_2_cdf. Path B (grad_reg_inc_beta, throughgrad_2F1) serves thelcdfandlccdfofbeta,beta_proportion,neg_binomialandstudent_t, and alsostudent_t_cdfand the autodiff ofinc_beta. Both paths return NaN gradients, or gradients wrong by O(1), at large shapes, atb ≫ a, and whereIis near 1.This PR replaces both paths with one implementation: the Boik and Robinson-Cox (1998) algorithm as TensorFlow Probability implements it. It uses a power series near the endpoints and a modified-Lentz continued fraction elsewhere. It differentiates both term by term and evaluates the prefactor in log space.
inc_beta_ddaandinc_beta_ddbbecome wrappers, andbeta_cdfcalls the root once instead of twice. No signature changes.The values of the distributions do not change. Only the gradients change.
I compiled both trees and ran them on the same 18 000 points in nine regions (details below):
log Iwrong by > 1e-2, path A,b ≫ alog Iwrong by > 1e-2, path B, negbinn > 200log I, branchdouble,var,fvar,fvar<fvar>grad_reg_inc_betaindoublebeta_lcdfper observation,α = β = 5beta_cdfper observation,α = β = 50The defects in the current code on
developThis section describes
developat5252d51d47. The reference is mpmath at 80 digits, computed by two independent routes: quadrature of the density, and numerical differentiation at 110 digits. The two routes agree to 60 digits at 54 check points. Alldevelopnumbers come from the compileddevelopheaders.1.
grad_reg_inc_betareturns NaN for every parameter whenbeta(a, b)underflows. Its callers passbeta(a, b)asbetaAB, and the function divides by it.beta(a, b)underflows whenais nearbanda + bis above about 1100. For example,beta_lcdf(y | 600, 600)has a NaN gradient for both shapes, and so doesinc_beta(a, b, z)with autodiff shapes. In the sweep region witha, bin [100, 12500] andznear the mode, whereIis of order 1, 1325 of 2000 points are NaN.2.
grad_reg_inc_betadrops the hypergeometric term whenz^a (1-z)^bunderflows. WhenC = z^a (1-z)^b / ais 0, the function skipsgrad_2F1and returnsI (log z - 1/a - ψ(a) + ψ(a+b)). WhenIis near 1, the dropped term is the whole answer, because2F1(a+b, 1; a+1; z)grows like(1-z)^(-b).beta_lcdf(0.758 | 352, 590)returnsd/dα = 0.705for a true-3.4e-138.neg_binomial_lcdf(132 | 313, 0.068)returnsd/dα = 0for a true-2.3.3.
inc_beta_ddaandinc_beta_ddbstop on an absolute threshold that can be met before the first term. Both stop the series whenfabs(summand) < 1e-10. The first summand contains the factor((a+1)/(a+b))^3, which is below 1e-10 forb ≫ a. The loop then exits at once and returns the first term.beta_cdf(1.8e-4 | 1.145, 6786)returnsd/dα = -0.203for a true-0.386, atI = 0.65. In the sweep region withb ≫ aand smallz, the gradient oflog Ihas an error above 1e-6 at 1301 of 2000 points, and above 1e-2 at 408.4.
inc_beta_ddaandinc_beta_ddbreflect on fixedzthresholds, not on which side is small. Forz > 0.75, and in other fixed bands, they evaluate1 - I_{1-z}(b, a)wherever the mass is. In the deep lower tail the result is thenI' ≈ 1times a bracket that must cancel to 1e-47, and the computed bracket is rounding noise of size 1e-15.beta_cdf(0.76 | 446, 5)returnsd/dα = 8.9e-16for a true-1.06e-47, so the gradient oflog(beta_cdf(...))is 2.5e+31. At some large-shape points the loop also reaches thek > 1e5iteration guard and throws, inside the range that the docstring calls tested.5. The existing unit tests assert wrong values.
inc_beta_ddb_test.cpppassesdigamma(a)as the fourth argument, which isdigamma(b), and its expected constants come from that call (reported in #2417).inc_beta_dda_test.cppandinc_beta_ddb_test.cppalso assert the output ofdevelopat points where it is wrong by orders of magnitude:1.8226241for a true-3.94e-5, and9.3959293for a true1.48e-8.grad_reg_inc_beta_test.cppexpectsd/db = -infatz = 1, whereI ≡ 1and the derivative is 0.What this PR does
The new body of
stan/math/prim/fun/grad_reg_inc_beta.hppis a C++ port of_betainc_partialsfrom TensorFlow Probability (tensorflow_probability/python/math/special.py, Apache-2.0; see the licence note below). The algorithm is from Boik and Robinson-Cox (1998), Derivatives of the Incomplete Beta Function, JSS 3(1). It evaluates the DLMF 8.17.22 continued fraction with the modified Lentz method and carries the derivatives of the partial numerators through the recurrence. Near the endpoints it uses the power series from Cephes, also differentiated term by term.Each defect above has a direct repair. The port evaluates the prefactor
z^a (1-z)^b / (a B(a, b))in log space, which removes defects 1 and 2. It applies the symmetry relationI_z(a, b) = 1 - I_{1-z}(b, a)at the mode for the continued fraction and at the mean for the series, which removes defect 4. It has no absolute threshold: the series stops ateps / aand the continued fraction at3 eps, which removes defect 3.The port changes the two stop tests of the TFP source, one in the series and one in the continued fraction. The code marks both changes. TFP stops when the value has converged. When
bis a positive integer, the series factor(n - b)and the continued-fraction numeratord_{2m}are exactly 0 atn = m = b. The value has then converged, but the derivatives still need the rest of the series. TFP's ownd/dbis off by 4.2e-4 at(2, 3, 0.25)and by 6.7 % at(10, 1, 0.5). Itsd/dais off by 5.6 % at(1, 100, 0.01), where the symmetry relation makesb' = 1. The port stops only when the derivative increments have also converged. Integer shapes are common, for example as initial values or as fixed shapes. I will report the TFP defect upstream.inc_beta_ddaandinc_beta_ddbbecome wrappers overgrad_reg_inc_betathat return one of the two derivatives.beta_cdfcallsgrad_reg_inc_betaonce, notinc_beta_ddaandinc_beta_ddbseparately.prim/fun.hppnow includesinc_beta_dda.hpp,inc_beta_ddb.hppandinc_beta_ddz.hpp; before, it reached them only throughprob/beta_cdf.hpp.grad_reg_inc_betakeeps itsbetaABargument for interface compatibility but no longer uses it.Net change: about 180 lines of algorithm replace 123.
Accuracy after the change
Same 18 000 points, same reference, both trees compiled with the same probe. The metric is the absolute error of the gradient of
log I.beta_lcdfreturns this gradient, and autodiff oflog(beta_cdf(...))gives it too. A relative error is not useful for a derivative that is 1e-300 ofI.a, b < 11 ≤ a, b ≤ 20,z < 0.75z > 0.75,a < 500b > a,b > 500,z ≤ 0.75b ≫ a,zsmalla, b,zuniforma, b,znear the moden ≤ 200200 < n ≤ 5000(1) Excluding points where
Iitself is subnormal in double.Where the derivative is not negligible (
|dI| / I ≥ 1e-3), the relative error is at most 6e-13 in every region exceptb ≫ awith smallz. There, one continued-fraction point at the symmetry switch reaches 3.7e-9. The four scalar typesdouble,var,fvar<double>andfvar<fvar<double>>give bit-identical values on both trees. On the branch, the autodiff types have the same error profile asdouble.Speed
Xeon E5-2680 v3 at 2.50 GHz, exclusive node,
performancegovernor, two rounds that agree within 2 %. Grid:a, bin [0.5, 60],zin [0.05, 0.95]. The benchmark loop adds a term that depends on the accumulator to every input, so the compiler cannot move the kernel out of the loop. I subtract the time of a baseline loop. The cycle counts of the baseline (6) and of3 digamma + beta(310) show that the compiler removed no call.Function level, net ns per call:
grad_reg_inc_betadouble, incl. 3 digamma + betagrad_reg_inc_betavar, value + gradgrad_reg_inc_betafvargrad_reg_inc_betafvar<fvar>inc_beta_ddadouble, incl. 2 digammaDistribution level,
N = 1000observations, sharedvarshapes, value plus reverse sweep, ns per observation:beta_cdfbeta_lcdfbeta_lccdfbeta_cdfbeta_lcdfbeta_lccdfneg_binomial_cdfneg_binomial_lcdfstudent_t_lcdfOn
develop, path B evaluates the 2F1 power series with threeexpand threelogcalls per term and no reflection. Atz = 0.998it needs 607 607 terms. The continued fraction of the branch costs about 600 cycles in addition to the digamma calls.Testing
Six test files use fixed references from the 80-digit mpmath computation. None uses finite differences, because finite differences cannot see these defects.
prim/fun/grad_reg_inc_beta_test.cpp: the two existing cases, with thez = 1expectation corrected to 0 and the tolerance tightened to 1e-12. New cases for each defect class:beta(a, b)underflow, prefactor underflow, integerb, and the tails.prim/fun/inc_beta_dda_test.cpp,prim/fun/inc_beta_ddb_test.cpp: rewritten from the reference at the same twelve points, with thedigamma_bargument corrected, plus regression points.rev/fun/inc_beta_test.cpp(new): shape gradients ofinc_betawithvararguments at the defect points.rev/prob/beta_cdf_test.cpp(new):beta_cdfshape partials at theb ≫ apoint, with both shapes as autodiff variables and with each shape alone.rev/prob/beta_cdf_log_test.cpp(new):beta_lcdfshape gradients at the NaN point, at the dropped-term point and at an integer shape.Regression check: I installed the
developheaders and ran these six files. All 6 suites fail, with 13 of 15 cases failing. With the headers of this branch, all 15 cases pass, both before and after the swap. The two cases that pass ondevelopare at points wheredevelopwas already correct.Licence note
The new body of
grad_reg_inc_beta.hppderives from TensorFlow Probability, which is Apache-2.0. The file carries the TFP copyright notice and refers tolicenses/tensorflow-probability-license.txt. It uses the same form as the Boost-derived code inprim/fun/log_modified_bessel_first_kind.hpp. The tree already contains Apache-2.0 code in vendored libraries (lib/tbb_2020.3,lib/benchmark_1.5.1). This file would be the first Apache-2.0-derived source file understan/.Known limits, not addressed here
beta_lccdfcomputes1 - Pnin linear space afterinc_beta. At(352, 590, 0.758)the doubleIis exactly 1, so the value is-infand the gradients are infinite. The true value islog(1 - I) ≈ -0.34. This defect is in the value code on both trees and needs a separate change (the symmetry relation for the value): Evaluate the incomplete beta complement without cancellation in the lccdf and Student t cdf functions #3433, stacked on this PR.Iis below about 1e-315 (subnormal), the relative error of the gradient rises to 1e-2. The reference itself has few correct digits there.Not included
grad_2F1, which other functions use.neg_binomial*_cdffunctions call the root. They need one derivative and already call the root once.Release notes
Replaces the incomplete beta gradient roots with a more stable continued-fraction implementation
Checklist
Copyright holder: Aalto University
The copyright holder is typically you or your assignee, such as a university or company. By submitting this pull request, the copyright holder is agreeing to the license the submitted work under the following licenses:
- Code: BSD 3-clause (https://opensource.org/licenses/BSD-3-Clause)
- Documentation: CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)
the basic tests are passing
./runTests.py test/unit)make test-headers)make test-math-dependencies)make doxygen)make cpplint)the code is written in idiomatic C++ and changes are documented in the doxygen
the new changes are tested