fix integrate_1d_gauss_kronrod gradient speed - #3393
Open
avehtari wants to merge 5 commits into
Open
Conversation
avehtari
marked this pull request as draft
September 6, 2026 18:17
avehtari
marked this pull request as ready for review
September 6, 2026 19:35
SteveBronder
reviewed
Sep 8, 2026
Contributor
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: 1495.986 CPU max MHz: 4114.4229 CPU min MHz: 1500.0000 BogoMIPS: 7189.04 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 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 |
Collaborator
Magical constants like this are a weird agent smell. Give me a minute to read into this more |
Member
Author
The justification why the constant should not be 1/2 or 1 is clear ,as they match saturated gradient for some models and link functions. There are other constants that could be used. This really as an ad hoc fix, but unfortunately the better fix would require changing Boost code to add absolute tolerance threshold. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Making this PR has been assisted by Claude. I have checked and edited all new code, comments, and PR text
Summary
The gradient computation for integrate_1d_gauss_kronrod calls the Boost adaptive Gauss Kronrod again, but Boost computes each parameter's gradient integral with the same Boost adaptive Gauss–Kronrod call. Boost's bisection criterion is relative to the leaf estimate, so a gradient component that is tiny relative to
fand dominated by round-off (e.g. the score of a saturated observation deep in a likelihood tail) never converges and bisects tomax_depth(2¹⁵ × 21 evaluations) on every call, although its contribution to∂ log Iis negligible. This can be fixed by shifting the integral integrand asg_i(x) = ∂f/∂θ_i (x) + c f(x)
and returning
∫ g_i − c I, whereIis the value integral already computed and c != 0 is a constantsuch that
∂f/∂θ_i ≈ −c·fdoes not occur for common integrands;c = 1is a bad choice because log-density gradients of logit-type likelihoods saturate at ±1 in the tails, which turns the shifted integrand back into noise. The inverse golden ratio is far from every integer and is not a structural constant of any link.As this is needed only for
integrate_1d_gauss_kronrod,integrate_1d_adjointgets an option whether the shift is used. The plainintegrate_1dandintegrate_1d_double_exponentialare unchanged: their L1-relative termination handles ordinary gradient integrands, and enabling the shift there costs 7–32 % more gradient evaluations on 10 of 35 suite integrands with no gain.Tests
Measured with the fix (same model, same point):
integrate_1dintegrate_1d49× faster gradients, results unchanged to 1e-11 (patched vs unpatched
GK: 1.0e-11). Per subject the counter shows 668 850 → 2 478 gradient
evaluations. The residual 2.75× is GK's per-integral cost on this
integrand (value-only GQ is 2.1× DE), not a gradient effect.
Effect on every integrand in the existing GK reverse-mode test suite
Integrand evaluations (value alone; all gradient components together)
and wall for value + gradients (mean of 200,
-O3), unpatched →patched. Same arguments and tolerances as the tests.
#var= numberof
varinputs (parameters + var endpoints).f1exp(x)+θ, [0.2, 0.7]f2exp(θ cos 2πx)+θ, var endpointsf3exp(x)+θ₀^2.5+2θ₁³+2θ₂, var endpointsf3, params onlyf101/(1+x⁴/1.7), (−∞, ∞), no paramsf11beta(5, 3), [0, 1]f11beta(3, 5), [0, 1]f12N(5.7, 1), (−∞, ∞)f13x+θ₀+θ₁, endpoints = paramsUnpatched, the noisy-gradient case does not merely hit
max_depth: itthen fails Stan's post-check (
error estimate 2.4e-13 exceeds max(rel_tol × L1, abs_tol)withL1 ≈ 0) and throws, i.e. in amodel block every proposal is rejected. Elsewhere the change is
neutral or a mild gain (heavy-tailed pdfs 15–35% fewer gradient
evaluations); the one regression is
f11(beta kernel: the gradientintegrands carry a
log xfactor that is easier thanfon its own),+14 % gradient evaluations at unchanged wall. All 17 pre-existing
tests pass at their tolerances.
A gradient component that is analytically zero but autodiffs to
round-off noise reproduces it without any likelihood machinery
(
cos² + sin² = 1). Added totest/unit/math/rev/functor/integrate_1d_gauss_kronrod_test.cppas
GradientShift_noisy_gradient(evaluation-count bound + accuracy;fails on the unpatched code, passes on the patched) together with
GradientShift_guards(exactly-zero integral → shift disabled; negativeintegral → shift active), and the existing 17 tests pass unchanged.
Side Effects
f. `f = spike(x)evaluations; shifted it re-resolves the spike, 189. Bound: gradient
cost ≤ (p + 1) × value cost, against 2^15 × 21 per component before.
inherits the value integral's absolute error (
≲ tol × L1(f)), so acomponent with
|∂I/∂θ| ≲ tol × L1(f)loses relative precision.Measured (
f = spike + ε θ x, spike width 0.01,tol = 1e-6):unshifted exact; shifted absolute error 3e-19 … 3e-18, i.e. relative
6e-15 at
ε = 1e-3down to 5e-10 atε = 1e-9— round-off level inpractice, because leaves that pass the value's test are usually far
below
tol. For HMC this is the right accuracy: value and gradiententer the Hamiltonian at the same absolute scale.
Release notes
integrate_1d_gauss_kronrod gradient computation was modified to have much improved worst performance timing
Checklist
Aki Vehtari
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