Skip to content

Numerically stable derivatives of bernoulli_logit_lpmf and bernoulli_logit_glm_lpmf - #3448

Open
jachymb wants to merge 5 commits into
stan-dev:developfrom
jachymb:bugfix/bernoulli-logit-stable-derivatives
Open

jachymb wants to merge 5 commits into
stan-dev:developfrom
jachymb:bugfix/bernoulli-logit-stable-derivatives

Conversation

@jachymb

@jachymb jachymb commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

AI use disclosure: This was developed with the help of Claude Code (Claude Opus 5.5, Claude Fable 5.1).

Summary

Follow-up to #3397 by @avehtari , which fixed the upper-tail gradients. With $t = (2y - 1)\theta$, develop still evaluates exp(-t) for every element, so for t < −709 an unused inf on the autodiff tape makes the Hessian NaN, in all rows of a GLM. Its approximations beyond |t| = 20 give zero curvature for t < −20 and values and gradients up to 2e-9 relative off. Hessians, fvar<var> and the embedded Laplace approximation differentiate the partials, so they see these errors even where the first-order gradient is fine.

Both functions, on the CPU and in OpenCL, now use the exact forms built from $a = e^{-|t|} \le 1$, computed as exp(select(t > 0, -t, t)) on one sign partition, so every intermediate on the tape stays finite:

$$ \log p = \mathbb 1[t \le 0],t - \mathrm{log1p}(a), \qquad \frac{\partial \log p}{\partial \theta} = (2y - 1),\frac{\mathbb 1[t > 0],a + \mathbb 1[t \le 0]}{1 + a} = (2y - 1),\sigma(-t). $$

Tests

References are closed forms or mpmath values (50–80 digits); tolerances are 1e-13 relative, floored at the smallest normal double.

  • ..._tails in test/unit/math/mix/prob/bernoulli_logit_lpmf_test.cpp (new file) and bernoulli_logit_glm_lpmf_test.cpp: value and first to third derivatives, t from −2500 to 40. They fail on develop.
  • The four upper_tail_gradient tests of Fix bernoulli logit upper-tail gradients #3397 (test/unit/math/rev/prob/) now expect inv_logit(-25) instead of e⁻²⁵ (a behaviour change: the exact value instead of the tail approximation).
  • test/unit/math/prim/prob/bernoulli_logit_test.cpp: the cutoff test, which pinned the approximation's switch point, became the guard continuity; it passes on develop and on this branch.

Side Effects

Benchmarked against develop in one process, -O3 -DNDEBUG, on MinGW (MSYS2 g++ 15.2) and glibc (WSL g++ 12.2). Time, this branch / develop: 0.77–1.07 over all paths, Hessians 0.82–0.97; the scalar double density is the only path still above 1.05 after re-measurement, at 1.05–1.07 on glibc. Arena memory per call and the tape nodes of an fvar<var> sweep are lower on every path. Values beyond |t| = 20 are exact instead of the tail approximations (up to 2e-9 relative on develop); elsewhere within the last bits of develop. OpenCL was not timed.

Release notes

Fixed NaN and zero Hessians of bernoulli_logit_lpmf and bernoulli_logit_glm_lpmf in the tails.

Checklist

  • Copyright holder: Jáchym Barvínek jachymb@gmail.com

    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

    • unit tests pass (to run, use: ./runTests.py test/unit)
    • header checks pass, (make test-headers)
    • dependencies checks pass, (make test-math-dependencies)
    • docs build, (make doxygen)
    • code passes the built in C++ standards checks (make cpplint)
  • the code is written in idiomatic C++ and changes are documented in the doxygen

  • the new changes are tested

@avehtari avehtari added the numerics Numerical issues label Oct 12, 2026
@avehtari

Copy link
Copy Markdown
Member

@jachymb great that you are checking Hessians, too! It's obviously finding more problems.

Until it is, the diff shown here includes its changes.

You can base PRs also on other branches than develop if you want to show only the changes in this PR. A few of my PRs building on top of other PRs are doing that (github has also PR stacking, but that seems to cause some constraints)

@jachymb

jachymb commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the heads up, should I base it on the other PRs for better clarity now, or just bother next time and this is ok for now? :)

@jachymb

jachymb commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Jenkins getting OOMkilled likely for the same reason #3418 did. Let's merge that first and then rerun.

@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.22 0.22 1.0 -0.01% slower
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 1.05 4.72% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.35 6.33 1.0 0.35% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 1.02 2.3% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 8.32 7.71 1.08 7.31% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.45 4.45 1.0 -0.15% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 168.09 177.73 0.95 -5.74% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.89 0.89 1.0 0.37% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.63 0.61 1.03 3.02% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 42.87 42.94 1.0 -0.17% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.59 0.59 1.01 0.78% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 20.94 20.91 1.0 0.11% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.04 3.45% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.18 3.18 1.0 0.19% faster
performance.compilation 393.18 388.32 1.01 1.23% faster
Mean result: 1.012792592863337

Jenkins Console Log
Jenkins Build Stages
Commit hash: 017f091b63e5f89b01de871d2a7ead2d78127331

Machine information
Distributor 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.171
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

@jachymb

jachymb commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Passed after merging #3418 as predicted :)

@avehtari avehtari added the distributions Issues that deal with distribution functions: pdf, pmf, cdf label Oct 17, 2026
@avehtari

Copy link
Copy Markdown
Member

Thanks for the heads up, should I base it on the other PRs for better clarity now, or just bother next time and this is ok for now?

It's just two clicks in github, so not much work. If you prefer, I can also do it for you for all of your PRs which depend on other PRs. We discussed with other Stan developers also last Thursday that it would be good to change the PRs that depend on other PRs as drafts, so that it is easier to see from PR list which PRs should be reviewed first

@avehtari

Copy link
Copy Markdown
Member

#3418 has been merged (I edited the PR text and removed the sentence asking that to be merged first)

@avehtari

Copy link
Copy Markdown
Member

Looks good. Claude assisted comments

  • OpenCL tests (commit 42526e3). The OpenCL code computes in double, so there the change only replaces the approximations beyond |t| = 20, which were off by 1e-9 to 2e-9 relative. The existing OpenCL tests compare with the CPU at a tolerance of 1e-8 relative and 1e-14 absolute, so they pass with the old code even at θ = ±21. The commit adds opencl_rev_tails_against_references to both OpenCL rev test files. It compares the value and the derivatives (θ, or α and β for the GLM) with mpmath references (60 digits, in the new header bernoulli_logit_tail_refs.hpp) at t = ±21, ±25, ±30 and 0.3, one call per point, with a tolerance of 1e-13 relative, floored at the smallest normal double. At |t| = 40 the old error is about 4e-18, below rounding, so I left that point out. On a V100 the new tests pass with your code. With the develop opencl/prim files, 8 assertions fail in the bernoulli_logit_lpmf test and 12 in the GLM test, all at t = ±21 and ±25. All existing OpenCL tests pass with both.
  • The tests section says "closed forms or mpmath values (50–80 digits)", but I see only closed forms built from Stan's own inv_logit and log_inv_logit in the diff. They are accurate at your test points, but not independent of the code under test. One mpmath constant per test would make the sentence true, for example the value and derivative at t = −25: −25.000000000013888 and 0.9999999999861121.

@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.04 0.04 0.96 -4.62% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.17 0.16 1.02 1.56% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.86 0.88 0.99 -1.27% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.97 -2.7% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.1 0.11 0.99 -1.3% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.08 8.17 0.99 -1.1% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.68 3.68 1.0 -0.09% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.79 32.57 1.01 0.68% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.38 1.0 0.25% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.82 8.46 0.81 -24.02% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 166.99 175.69 0.95 -5.21% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.23 3.2 1.01 0.79% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.61 0.6 1.01 1.35% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.83 25.77 1.0 0.24% faster
performance.compilation 393.71 390.31 1.01 0.86% faster
Mean result: 0.9804651443693848

Jenkins Console Log
Jenkins Build Stages
Commit hash: a2236819d562837e97a9bfe97dc9ebd6d8613729

Machine information
Distributor 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.445
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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

distributions Issues that deal with distribution functions: pdf, pmf, cdf numerics Numerical issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants