Repository navigation
Conversation
|
I'll be away for the next two weeks, but made this PR to avoid duplicated work |
|
The improved |
|
@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
|
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 |
Port the Boik and Robinson-Cox continued fraction (as in TensorFlow Probability) to prim grad_reg_inc_beta, route inc_beta_dda, inc_beta_ddb and fwd inc_beta through it, and test against fixed mpmath references.
6e1938c to
2764cf5
Compare
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: 43 bits physical, 48 bits virtual CPU(s): 256 On-line CPU(s) list: 0-255 Thread(s) per core: 2 Core(s) per socket: 64 Socket(s): 2 NUMA node(s): 2 Vendor ID: AuthenticAMD CPU family: 23 Model: 49 Model name: AMD EPYC 7742 64-Core Processor Stepping: 0 Frequency boost: enabled CPU MHz: 1497.222 CPU max MHz: 3416.0681 CPU min MHz: 1500.0000 BogoMIPS: 4491.85 Virtualization: AMD-V L1d cache: 4 MiB L1i cache: 4 MiB L2 cache: 64 MiB L3 cache: 512 MiB NUMA node0 CPU(s): 0-63,128-191 NUMA node1 CPU(s): 64-127,192-255 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: Mitigation; untrained return thunk; SMT enabled with STIBP protection 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; Retpolines; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected 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 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 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 ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sev sev_es 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 |
|
Action: Not Ready for Human Review Commit checked: SummaryThank you for this work on the incomplete beta gradients and for the detailed write-up of the defects on develop. The PR replaces the two implementations of the shape derivatives of the regularized incomplete beta function with one continued-fraction implementation based on TensorFlow Probability. I read the changed code and tests at 2764cf5 and the replaced code on develop at the merge base 5792530. The output of each run is in this gist.
Claims and EvidenceEach section below lists facts from the PR summary and discussion that an agent was able to confirm, partially confirm, or not confirm at all, or that a run of the code in the PR contradicted. Confirmed FactsFACT: The PR fixes #2417Quote:
STATUS: ConfirmedIssue #2417 reports two things. Evidence:The PR's test What I ran: FACT: At z = 1 the shape gradients of inc_beta are 0 and the z gradient is +infQuote:
STATUS: ConfirmedAt the head, Evidence:The tests What I read: The lines of What I ran: Both tests pass in the head run of the four prim test files. FACT: With a zero tangent on z, the fvar tangent of inc_beta at z = 1 is NaNQuote:
STATUS: ConfirmedAt the head, fwd Evidence:The fwd What I read: The fwd Partially Confirmed FactsFACT: Defect 1: grad_reg_inc_beta returns NaN when beta(a, b) underflowsQuote:
STATUS: Partially ConfirmedThe division follows from the code. Evidence:The test What I read: On develop, grad_reg_inc_beta.hpp L40-L57 computes What I ran: Request: Could you add a test of the defect that compiles on develop, for example the checks of the 9-argument FACT: Defect 2: grad_reg_inc_beta drops the hypergeometric term when the prefactor underflowsQuote:
STATUS: Partially ConfirmedThe skipped call follows from the code. Evidence:The test What I read: On develop, grad_reg_inc_beta.hpp L43-L57 sets What I ran: The same runs as defect 1. Request: Could you add a test at FACT: Defect 3: inc_beta_dda and inc_beta_ddb stop on an absolute threshold that can be met before the first termQuote:
STATUS: Partially ConfirmedThe threshold follows from the code. Evidence:The regression tests in What I read: On develop, inc_beta_dda.hpp L64-L83 and inc_beta_ddb.hpp L59-L75 set What I ran: The PR's Request: Could you move the vectorized FACT: Defect 4: inc_beta_dda and inc_beta_ddb reflect on fixed z thresholdsQuote:
STATUS: Partially ConfirmedThe fixed thresholds follow from the code. Evidence:The regression tests at What I read: The reflection conditions on develop are at inc_beta_dda.hpp L44-L62, and the guard that throws for What I ran: The same runs as defect 3. Request: Could you make the FACT: Defect 5: the existing unit tests assert wrong valuesQuote:
STATUS: Partially ConfirmedThe develop tests show each point. Evidence:The develop tests and the PR's rewritten tests. What I read: I read the three test files on develop at 5792530 and the rewritten files at the head, at the lines linked in the finding. What I ran: The PR's Request: The mpmath script requested below would back the true values. FACT: The four scalar types give bit-identical values on both treesQuote:
STATUS: Partially ConfirmedFor Evidence:The rev and fwd What I read: At the head, rev/fun/inc_beta.hpp L26-L28, grad_reg_inc_beta.hpp L498-L499, and fwd/fun/inc_beta.hpp L36-L54. Request: Could you add or link the code that compares FACT: Regression check: the tests fail on develop and pass on the branchQuote:
STATUS: Partially ConfirmedThree of the six files named in the description are in this PR ( Evidence:The PR's test files. What I ran: I ran each test file with Request: Could you update the regression check for this part, giving the files and counts for this PR alone? FACT: inc_beta_ddz returns infinity instead of throwing where the density is infiniteQuote:
STATUS: Partially ConfirmedThe policy change follows from the code. Evidence:The test What I read: What I ran: Request: Could you put the container tests of FACT: The generated cdf, lcdf, and lccdf tests of six families passQuote:
STATUS: Partially ConfirmedThe comment reports a run on the branch before the split. Evidence:The generated What I ran: Request: Could you note that the rev and mix suites in this sentence are part of #3489? Not Verified FactsFACT: The test references come from an 80-digit mpmath computation by two independent routesQuote:
STATUS: Not VerifiedThe expected values in Evidence:The constants are in the tests. Request: Could you add the mpmath script that produces the expected constants (both routes), for example under FACT: Accuracy over 18 000 points in nine regionsQuote:
STATUS: Not VerifiedThe summary table and the Accuracy section report counts of non-finite and inaccurate gradients on develop, and worst errors on the branch (1e-11 absolute, 3.7e-9 relative, 6e-13 relative outside Evidence:The sweep, the probe, and the reference values at the 18 000 points are missing. Request: Could you add the sweep script and the probe program, with the commands that build them against develop and against this branch? FACT: Function-level speedups of 2.2x to 68xQuote:
STATUS: Not VerifiedThe description gives net ns per call on develop and on the branch for Evidence:The benchmark code is missing. Request: Could you add the benchmark, for example as a google-benchmark file, with the command and compiler flags used? FACT: Distribution-level speedups of 1.1x to 40xQuote:
STATUS: Not VerifiedThe description gives ns per observation for the cdf, lcdf, and lccdf of Evidence:The benchmark code is missing. Request: Could you add the benchmark and say which rows apply to this PR alone? FACT: Path B needs 607 607 terms at z = 0.998, and the continued fraction costs about 600 cyclesQuote:
STATUS: Not VerifiedThe PR does not include code that counts the terms of the 2F1 series on develop or the cycles of the continued fraction. Evidence:Code that counts terms and cycles is missing. Request: Could you add the code that produced the term count and the cycle count, or drop the two numbers? FACT: TFP's own derivatives are off at integer shapesQuote:
STATUS: Not VerifiedThe PR does not include code that runs TensorFlow Probability. Evidence:Code that evaluates TFP at the three points is missing. Request: Could you link the script that evaluated TFP at these points, or the upstream report once it is filed? FACT: The new ibeta_derivative call is bit-identical to the default at 180 360 grid pointsQuote:
STATUS: Not VerifiedThe PR does not include or link the grid comparison of the two calls. Evidence:The comparison script is missing. Request: Could you link the script that compared the two calls on the grid? FACT: Speed ratios of the original PR over the version with the rev changesQuote:
STATUS: Not VerifiedThe comment gives ratios between two versions of the branch for first-order reverse mode, one-shape cases, Evidence:The benchmark code is missing. Request: Could you link the benchmark behind this table, or move the table to #3489 where the rev code is? FACT: Many cdfs are now 10x fasterQuote:
STATUS: Not VerifiedThe comment includes a heatmap image. Evidence:The benchmark behind the heatmap is missing. Request: Could you link the benchmark that produced the heatmap? Description vs CodeEach section below lists facts from the PR summary and discussion that an agent was able to confirm, partially confirm, or not confirm at all, or that a run of the code in the PR contradicted. Confirmed FactsFACT: This PR is part 1 of the splitQuote:
STATUS: ConfirmedThe PR changes FACT: The callers of path A and path B on developQuote:
STATUS: ConfirmedOn develop, FACT: Both paths go through one implementation, with inc_beta_dda and inc_beta_ddb as wrappersQuote:
STATUS: Confirmed
FACT: The new grad_reg_inc_beta evaluates a continued fraction with the modified Lentz method and a power series near the endpoints, both differentiated term by termQuote:
STATUS: ConfirmedThe doc comment names Boik and Robinson-Cox (1998) as implemented in TensorFlow Probability (L362-L364). FACT: The prefactor is evaluated in log spaceQuote:
STATUS: ConfirmedThe power series computes FACT: The power series switches to the symmetry relation at the meanQuote:
STATUS: ConfirmedWith FACT: The series stops at eps / a and the continued fraction at 3 epsQuote:
STATUS: ConfirmedThe power series sets FACT: grad_reg_inc_beta keeps betaAB but no longer uses itQuote:
STATUS: ConfirmedThe templated overload leaves the parameter unnamed (L426), and the doc comment says it is accepted for interface compatibility and not used (L417-L418). FACT: The values of the distributions do not changeQuote:
STATUS: ConfirmedThe PR does not change any file under FACT: The grad_reg_inc_beta test changesQuote:
STATUS: Confirmed
FACT: The inc_beta_dda and inc_beta_ddb tests are rewritten at the same twelve pointsQuote:
STATUS: ConfirmedBoth files keep the shapes 1.5, 15000, 1.25, and 12500 and the FACT: No change to grad_2F1 or to how the neg_binomial cdfs call the rootQuote:
STATUS: ConfirmedThe PR does not change FACT: The commit routes inc_beta_dda, inc_beta_ddb, and fwd inc_beta through grad_reg_inc_betaQuote:
STATUS: Confirmed
Partially Confirmed FactsFACT: No signature changesQuote:
STATUS: Partially ConfirmedThe 9-argument Request: Could you reword this to say that existing calls keep their form, and list the new overloads? FACT: The code marks both changes to the TFP stop testsQuote:
STATUS: Partially ConfirmedBoth stop tests also wait for the Request: Could you add a note at the two stop tests saying that they differ from TFP, or reword the description? FACT: prim/fun.hpp now includes the three derivative headersQuote:
STATUS: Partially Confirmed
Request: Could you change "only through FACT: About 180 lines of algorithm replace 123Quote:
STATUS: Partially ConfirmedThe new code is longer than the code it replaces. Request: Could you say how the 180 and 123 lines were counted, or drop the sentence? FACT: beta_lccdf computes 1 - Pn in linear spaceQuote:
STATUS: Partially Confirmed
Request: Could you point to a test of the value at Not Verified FactsFACT: Three new rev test filesQuote:
STATUS: Not Verified
Request: Could you mark these three files as part of #3489 and #3490 in the Testing section? Contradicted FactsFACT: beta_cdf calls grad_reg_inc_beta onceQuote:
STATUS: ContradictedAt this commit Request: Could you mark the statements that describe #3489 and #3490, such as this one? FACT: The continued fraction switches to the symmetry relation at the modeQuote:
STATUS: ContradictedThe continued fraction switches when Request: Could you change "at the mode" to the threshold FACT: The file carries the TFP copyright notice and refers to the licence fileQuote:
STATUS: ContradictedAt this commit Request: Could you add the TFP copyright notice to Not Checked
|
|
Reply to @stevieb-bot. I changed the PR text and the tests, and added the scripts behind the numbers. In the code, I changed only comments and the license notice of ScriptsThe scripts are in https://github.com/avehtari/stan-pr-checks/tree/8b80a636364b7751bbf3553e63cf18d010f394c2/pr3409, and its README has one section per claim with the commands and the expected output. The directory has:
I ran all of them again on Numbers that changed in the rerun
At At the worst relative errors the two reference routes agree to 60 digits, so the errors are in the code. I fixed one error in the reference script. Where Partially confirmed and not verified facts
Description vs code
TestsOn Triton with g++ 14.3, these pass with the new code:
After that run I changed only comments, the year of the license notice and the name of one test. Then I ran the regression check on a laptop (g++ 11.4). All 25 tests pass with the new code, and 15 of 19 fail with the develop headers. |

EDIT: 2026-10-29 updated after revision
Replace the incomplete beta gradient roots with a continued-fraction implementation from TensorFlow Probability.
Fixes #2417.
This PR was Claude assisted.
The scripts behind the numbers in this text are in https://github.com/avehtari/stan-pr-checks/tree/8b80a636364b7751bbf3553e63cf18d010f394c2/pr3409. Its
README.mdhas one section per claim, with the commands and the expected output.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. This text calls such a function a gradient root, or a root.develophas two separate implementations of these derivatives.beta_cdf,neg_binomial_cdfandneg_binomial_2_cdfcall path A (inc_beta_dda,inc_beta_ddb). Path B (grad_reg_inc_beta, throughgrad_2F1) has these callers: thelcdfandlccdfofbeta,beta_proportion,neg_binomialandstudent_t;student_t_cdf; and the autodiff ofinc_beta. At large shapes, atb ≫ aand nearI = 1, both paths return NaN gradients or gradients wrong by O(1). Both paths also throw at some points.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, and differentiates both term by term. It evaluates the prefactor in log space.
inc_beta_ddaandinc_beta_ddbbecome wrappers. The callers inprim/probstay as they are, and so do the values of the distributions: the PR changes gradients only.I compiled the merge base
579253050c("develop" below) and this PR, and ran both on the same 18 000 points in nine regions:log Iwrong by > 1e-2, path A,b ≫ alog Iwrong by > 1e-2, path B, negbinn > 200log I(2)grad_reg_inc_betaindoublebeta_lcdfper observation,α = β = 5beta_cdfper observation,α = β = 50(1) The table leaves out the 528 points where the double
Iis 0.(2) The table leaves out the 14 points where
Iis subnormal.The defects in the current code on
developThis section describes
developat the merge base579253050c, compiled. The reference is mpmath, computed by two independent routes: quadrature of the density at 80 digits, and numerical differentiation at 110 digits. At the 21 points of the unit tests the two routes agree to at least 60 digits.1.
grad_reg_inc_betareturns NaN for every parameter whenbeta(a, b)underflowsIts callers pass
beta(a, b)asbetaAB, and the function divides by it.beta(a, b)underflows whenais nearbanda + bis above about 1100. The shape gradients ofbeta_lcdf(0.5 | 600, 600)are then NaN, and so are those ofinc_beta(600, 600, 0.5)with autodiff shapes. In the sweep region witha, bin [100, 12500] andznear the mode, whereIis of order 1, path B is NaN at 1325 of 2000 points.The function also forms
c3 = B(a, b) Iand divides byB(a, b)at the end. Whenc3underflows, both partials are 0. Atneg_binomial_lcdf(132 | 313, 0.068),I = 1e-262andB(a, b) I = 2e-381, and develop returnsd/dα = 0for a true-2.40.2.
grad_reg_inc_betadrops the hypergeometric term whenz^a (1-z)^bunderflowsWhen
C = z^a (1-z)^b / ais 0, the function skipsgrad_2F1and returnsI (log z - 1/a - ψ(a) + ψ(a+b)). NearI = 1the 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.3.
inc_beta_ddaandinc_beta_ddbstop on an absolute threshold that the first term can meetBoth stop the series when
fabs(summand) < 1e-10. The first summand contains the factor((a+1)/(a+b))^3, which is below 1e-10 forb ≫ a, so the loop 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, thed/dαpart of 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 fixedzthresholdsFor
z > 0.75, and in other fixed bands, they evaluate1 - I_{1-z}(b, a)whether or notIis small. In the lower tail, the result isI' ≈ 1times a bracket that must cancel to 1e-47. The computed bracket is rounding noise of size 1e-15.beta_cdf(0.76 | 446, 5)returnsd/dα = -1.8e-15for a true-1.06e-47, which makes the gradient oflog(beta_cdf(...))-4.4e+31.At 98 of the 18 000 sweep points the loop reaches its iteration limit and throws "did not converge", inside the range that the docstring calls tested. Path B throws at 24 other points, from
hypergeometric_2F1.5. The existing unit tests assert wrong values
inc_beta_ddb_test.cpppassesdigamma(a)as the fourth argument,digamma_b, and its expected constants come from that call (reported in #2417).inc_beta_dda_test.cppandinc_beta_ddb_test.cppalso assert wrong output ofdevelop: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 license 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 a power series, also differentiated term by term.The repairs of the defects:
z^a (1-z)^b / (a B(a, b))in log space;eps / aand the continued fraction at3 eps, both relative;I_z(a, b) = 1 - I_{1-z}(b, a)forz ≥ (a + 1) / (a + b + 2)in the continued fraction, and forzat or above the meana / (a + b)in the series.The port differs from the TFP source in three places, and comments in the code mark each one.
b, the series factor(n - b)and the continued-fraction numeratord_{2m}are 0 atn = m = b. The value has then converged while the derivatives still need the rest of the series. In TFP 0.25.0,d/dbis off by 4.2e-4 at(2, 3, 0.25)and by 6.7 % at(10, 1, 0.5), andd/daby 5.6 % at(1, 100, 0.01), where the symmetry relation makesa = 1the integer shape. Integer shapes are common as initial values and as fixed shapes. I have not filed the TFP report yet.z = 0.5(TFP: 0.95). Nearz = 0.95the series needs most of its 600-term limit, where the continued fraction needs tens.(a + 1) / (a + b + 2). TFP switches at the mode(a - 1) / (a + b - 2), which is above 1 forb < 1.grad_reg_inc_beta<GRAD_RIB>computes only the requested partials (G1fora,G2forb,BOTH).inc_beta_ddausesG1andinc_beta_ddbusesG2. Fwdinc_betarequests the partials of its autodiff shapes, and takes thezpartial frominc_beta_ddzonly whenzis an autodiff type.inc_beta_ddz(double, double, double)calls Boost'sibeta_derivativewith a policy that returns infinity on overflow, and keeps all other defaults. Where the density is infinite (z = 1withb < 1,z = 0witha < 1) it returns+inf; develop throws there. I compared it with the default call on a grid of 183 600 points. At the 180 360 points where the default does not throw, the results are bit-identical. At the other 3 240 points it returns+inf.Existing calls keep their form. The nine-argument
grad_reg_inc_beta(g1, g2, ...)and the five-argumentinc_beta_ddaandinc_beta_ddbtake the same arguments in the same order, andgrad_reg_inc_betakeeps itsbetaABargument without using it. The template signatures change, and the PR adds overloads:grad_reg_inc_beta<GRAD_RIB>(a, b, z, digamma_a, digamma_b, digamma_ab, betaAB), which returns the requested partials;inc_beta_ddaandinc_beta_ddz;inc_beta_ddaandinc_beta_ddbtake five template types instead of one, and returnauto;inc_beta_ddzfordoubleis an overload instead of an explicit specialization;inc_betais one constrained template instead of seven overloads.prim/fun.hppnow includesinc_beta_dda.hpp,inc_beta_ddb.hppandinc_beta_ddz.hpp. On develop,prim.hppreached them only throughprob/beta_cdf.hpp,prob/neg_binomial_cdf.hppandprob/neg_binomial_2_cdf.hpp.Accuracy after the change
This section uses the 18 000 points and the mpmath reference of the summary. I compiled both trees with the same probe (g++ 11.4,
-O2), which calls each root on its own, so a throw marks only that root. The metric is the absolute error of the gradient oflog I.beta_lcdfreturns this gradient, and autodiff oflog(beta_cdf(...))gives it too. A relative error says little for a derivative that is 1e-300 ofI. A point counts once if either partial fails, andnis the number of points where the doubleIis not 0.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) The column leaves out the points where
Iis subnormal in double: 1, 11 and 2 points. There the error rises to 7e-3, because subnormal doubles have few significant bits.Where the derivative is not negligible (
|dI| / I ≥ 1e-3), the relative error of this PR is at most 3.8e-12, at large shapes. At the worst point of each region the two reference routes agree to 60 digits.Scalar types, 2 007 points: with both shapes as autodiff arguments, the shape gradients of
inc_betainvar,fvar<double>andfvar<fvar<double>>are bit-identical to thedoubleroot, on both trees. With onefvarshape, fwdinc_betacalls the one-sided root, which differs from the two-sided root by at most 2.5e-13 relative. With onevarshape the gradient stays bit-identical, because revinc_betais unchanged in this PR.Speed
Xeon Gold 6230 at 2.10 GHz, exclusive node,
performancegovernor, g++ 14.3,-O3, Triton job 21271376; the two rounds agree within 1 %. 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 (5) and of3 digamma + beta(330) 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. The distribution code is the same on both trees; the gain comes from the new root.beta_cdfbeta_lcdfbeta_lccdfbeta_cdfbeta_lcdfbeta_lccdfneg_binomial_cdfneg_binomial_lcdfstudent_t_lcdfHere
beta_cdfstill callsinc_beta_ddaandinc_beta_ddbseparately; #3490 changes it to one call. Thecdfrows measure time only: the product of 1000 cdfs underflows, and the gradient is 0 on both trees.Testing
The new tests compare with fixed references from the mpmath computation above. None of them uses finite differences, which do not detect these defects. The tests of the new overloads are in their own files, so that the defect tests compile against develop.
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, the tails, and a point where develop throws.prim/fun/grad_reg_inc_beta_one_sided_test.cpp(new): theGRAD_RIBrequests at the same points.prim/fun/inc_beta_dda_test.cpp,prim/fun/inc_beta_ddb_test.cpp: rewritten from the reference at the twelve points of the old tests, with thedigamma_bargument corrected, plus regression points and a point where develop throws.prim/fun/inc_beta_dda_vectorized_test.cpp,prim/fun/inc_beta_ddz_vectorized_test.cpp(new): the container overloads.prim/fun/inc_beta_ddz_test.cpp:+infwhere the density is infinite.rev/prob/beta_cdf_log_test.cpp(new):beta_lcdfshape gradients at(0.5 | 600, 600), at(0.758 | 352, 590)and at integer shapes.rev/prob/neg_binomial_cdf_log_test.cpp:d/dαofneg_binomial_lcdf(132 | 313, 0.068).Regression check (g++ 11.4): I replaced the six headers of this PR with their versions at
579253050c. Then 15 of the 19 tests in the six files that compile against develop fail. The four that pass, three older tests and the newgrad_reg_inc_beta.moderate, test points where develop is right. The three files of the new overloads do not compile against develop. With the headers of this PR, all 25 tests pass.On Triton (g++ 14.3) these also pass:
inc_betaandgrad_2F1;inc_betaandgrad_reg_inc_beta;beta,beta_proportion,neg_binomial,neg_binomial_2andstudent_t;test/probtests ofbeta,beta_proportion,binomial,neg_binomial,neg_binomial_2andstudent_t(256 programs);test-math-dependencies,test-headersand doxygen.License 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, which this PR adds, as the Boost-derived code inprim/fun/log_modified_bessel_first_kind.hppdoes. 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, for a truelog(1 - I) ≈ -316.2. The defect is in the value code on both trees; Evaluate the incomplete beta complement without cancellation in the lccdf and Student t cdf functions #3433 repairs it.ypartial ofbeta_lcdf(0.5 | 600, 600)and theβpartial ofneg_binomial_lcdf(132 | 313, 0.068)are NaN on both trees. Both come from the density terms of the two lcdfs. I will fix them in a separate PR.Iis subnormal, the error of the gradient oflog Irises to 7e-3 (see the accuracy table).Not included
grad_2F1, which other functions use, is unchanged.prim/probchange in Move the beta, neg_binomial and student_t cdfs to the new grad_reg_inc_beta (part 3 of #3409) #3490.Release notes
Replaced the incomplete beta gradient roots with a continued-fraction implementation that does not return NaN or throw at large shapes.
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