Skip to content

Embedded Laplace: closed-form derivatives for the built-in likelihoods - #3471

Open
avehtari wants to merge 2 commits into
developfrom
feature/laplace-analytic-likelihood-derivatives
Open

avehtari wants to merge 2 commits into
developfrom
feature/laplace-analytic-likelihood-derivatives

Conversation

@avehtari

@avehtari avehtari commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #3287. Replaces #3291.

The embedded Laplace approximation uses nested autodiff for the gradient, Hessian and third derivative of the log likelihood with respect to theta, also for the built-in likelihoods. This PR adds closed forms for the likelihoods of laplace_marginal_poisson_log_lpmf, laplace_marginal_bernoulli_logit_lpmf, laplace_marginal_neg_binomial_2_log_lpmf (scalar or per-group eta) and laplace_marginal_neg_binomial_2_log_summary_lpmf.

This PR was Claude assisted

Mechanism. A likelihood functor F declares closed-form derivatives by specializing the new trait laplace_likelihood::analytic_derivatives<F> with the static functions theta_grad(), neg_hessian_diag() and third_diff(). They take theta and the arguments of F::operator(), without the message stream. theta_grad(), diagonal_hessian(), block_hessian() and third_diff() in laplace_likelihood::internal each get a second overload, which a require_ constraint selects when F specializes the trait and all arguments are arithmetic. Otherwise the autodiff overload runs, so user-defined likelihoods and var arguments behave as before. The Newton iterations always pass arithmetic arguments, and third_diff() runs only when no likelihood argument is a var.

Formulas. The Hessians of these likelihoods are diagonal. With n_g observations and count sum counts_g in group g:

  • Poisson: m_g = n_g exp(theta_g + mean_g); gradient counts_g - m_g, negative Hessian m_g, third derivative -m_g.
  • Bernoulli logit: p_g = inv_logit(theta_g + mean_g), q_g = inv_logit(-theta_g - mean_g); gradient counts_g - n_g p_g, negative Hessian n_g p_g q_g, third derivative -n_g p_g q_g (q_g - p_g).
  • Negative binomial: s_g = counts_g + eta_g n_g, p_g = inv_logit(theta_g + mean_g - log(eta_g)), q_g = 1 - p_g; gradient counts_g - s_g p_g, negative Hessian s_g p_g q_g, third derivative -s_g p_g q_g (q_g - p_g).

Computing q_g as inv_logit(-x) avoids cancellation and keeps the values finite where exp(theta) overflows. block_hessian() returns the sparsity pattern of the autodiff version (full blocks of size hessian_block_size, zeros off the diagonal), so the solvers get the same structure as before.

Not changed. With a var likelihood argument, compute_s2(), diff_eta_implicit() and ll_arg_grad() still use autodiff.

Speed. I timed the value and the gradient with respect to the 2 hyperparameters of a squared-exponential GP covariance, with 2 observations per group and hessian_block_size = 1 (g++ 14.3, -O3). Each entry is the time of this PR divided by the time of develop, for two runs:

n Poisson value Poisson gradient Bernoulli value Bernoulli gradient
10 0.58, 0.57 0.58, 0.56 0.58, 0.55 0.58, 0.57
50 0.68, 0.68 0.71, 0.69 0.69, 0.69 0.73, 0.73
200 0.90, 0.89 0.91, 0.90 0.94, 0.90 0.94, 0.92
1000 1.04, 1.04 1.03, 1.02 0.99, 1.01 0.99, 1.00

For the negative binomial (eta = 3), the last column is the gradient with respect to the hyperparameters and eta, with eta a var:

n value gradient gradient, eta a var
10 0.47, 0.48 0.46, 0.47 0.59, 0.60
50 0.53, 0.53 0.56, 0.55 0.67, 0.67
100 0.63, 0.63 0.68, 0.69 0.76, 0.77
200 0.74, 0.75 0.80, 0.82 0.86, 0.87
1000 0.92, 0.97 0.97, 0.97 0.97, 0.98

The gain is largest for small n. For large n, the O(n³) factorization takes most of the time.

Tests

The new file test/unit/math/laplace/laplace_analytic_derivatives_test.cpp has five tests:

  • trait: the trait is set for the four built-in functors and not for a lambda, and a var argument selects the autodiff overload.
  • used_by_laplace_marginal: a test functor with the Poisson formulas counts the calls to its specialization, and laplace_marginal() must call it.
  • equal_to_autodiff: theta_grad(), diagonal_hessian(), block_hessian() (block sizes 1 and 2, sparsity pattern included) and third_diff() must equal autodiff through the same functor behind a lambda. Cases: all four functors, several observations per group, scalar and per-group eta, and theta + mean shifted by 0 and ±30 (relative tolerance 1e-12).
  • finite_at_large_theta: at |theta + mean| up to 800, where exp(theta) overflows, the Bernoulli and negative binomial derivatives stay finite and equal to autodiff.
  • end_to_end_equal_to_autodiff: the values and gradients of the three laplace_marginal_tol_*_lpmf functions must equal those of laplace_marginal_tol() and the autodiff version, for solvers 1 to 3, Hessian block sizes 1 and 2, and eta a var for the negative binomial (relative tolerance 1e-7).

The existing expect_ad tests of the three likelihoods now run the closed-form derivatives in the Newton iterations.

Side Effects

Results differ from develop by rounding, by up to 6e-9 relative in the benchmark above. A later change of the block structure of W_r (#3422) must also cover the new block_hessian() overload.

Release notes

The embedded Laplace functions for the Poisson, Bernoulli logit and negative binomial use closed-form derivatives, which makes them up to 2 times faster for a small latent dimension.

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

    • 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

@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.23 1.0 -0.23% slower
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 0.99 -0.62% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.29 6.28 1.0 0.15% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 1.0 0.25% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 8.26 8.27 1.0 -0.04% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.45 4.45 1.0 0.02% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 217.71 216.9 1.0 0.37% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.89 0.89 1.0 0.09% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.61 0.61 0.99 -0.73% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 42.7 44.79 0.95 -4.9% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.58 0.59 0.98 -1.88% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 20.89 20.89 1.0 0.03% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.0 -0.11% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.2 3.17 1.01 1.02% faster
performance.compilation 367.65 365.13 1.01 0.69% faster
Mean result: 0.9962807287539738

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:                           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:                                 1494.150
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

@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 1.03 2.62% faster
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.16 0.99 -0.54% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.87 0.86 1.01 1.22% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.98 -1.8% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 0.99 -0.83% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.07 8.27 0.98 -2.39% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.62 3.67 0.99 -1.16% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 34.18 33.46 1.02 2.1% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.39 0.99 -1.14% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.82 6.81 1.0 0.25% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 170.61 167.52 1.02 1.81% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.23 3.26 0.99 -0.9% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.61 0.6 1.0 0.15% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.91 25.84 1.0 0.29% faster
performance.compilation 387.26 373.68 1.04 3.51% faster
Mean result: 1.0024041854095442

Jenkins Console Log
Jenkins Build Stages
Commit hash: f0fa1549624776581808289c9720367089c95ef9

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:                                 1496.758
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reuse direct reverse mode autodiff specializations for known laplace distributions

2 participants