Skip to content

Embedded Laplace: accept rank-deficient Hessian blocks in solver 1 and fix solver fallback reporting - #3419

Open
jachymb wants to merge 6 commits into
stan-dev:developfrom
jachymb:bugfix/laplace-solver-fixes
Open

jachymb wants to merge 6 commits into
stan-dev:developfrom
jachymb:bugfix/laplace-solver-fixes

Conversation

@jachymb

@jachymb jachymb commented Sep 26, 2026

Copy link
Copy Markdown
Contributor

AI use disclosure: The code as well as this commentary was done with the help of claude Fable 5.1

This PR bnudles two kinda independent changes (improving the solver and improving fallback reporting; one per commit) but they both improve embedded Laplace implementation so I decided to put them together

Summary

block_matrix_sqrt takes the square root of each Hessian block with Eigen::SelfAdjointEigenSolver, clamping eigenvalues that are negative only at rounding level, and the solver-fallback path decides between throwing and logging before its std::call_once. Solver 1 no longer fails on rank-deficient blocks (more latent variables than observations), which previously cost one wasted Hessian and a fallback to solver 2 on every such call, and a solver failure is now reported correctly with or without a message stream.

One commit per fix:

  • Square root. W is the negative Hessian of a log-concave likelihood, symmetric positive semi-definite, and rank deficient whenever a block has more latent variables than observations, which is the normal case for a dense coefficient block. The Schur-based code threw on any negative Schur diagonal entry, which such blocks produce by rounding. The tolerance is -block_size * epsilon * max(|eigenvalues|, 1); genuinely indefinite blocks still throw and trigger the fallback as before. The non-finite check fired only when no entry was finite (isFinite().any()) and now fires when any entry is not. The unsupported/Eigen/MatrixFunctions include is no longer needed.
  • Fallback. log_solver_fallback threw whenever the message stream was null even with allow_fallthrough set, and because it ran inside std::call_once, a failure with allow_fallthrough unset after an earlier logged fallback was not reported at all and ended in the unrelated "solver not valid" error. Now throw_solver_failure throws with the failing solver's reason when fallthrough is disabled; otherwise the fallback is logged once if a stream exists.

Tests

  • test/unit/math/laplace/block_matrix_sqrt_test.cpp (new): positive definite blocks; rank-deficient blocks, accepted where they threw before; an indefinite block and a block with a NaN entry both throw, the latter passed the old finiteness check.
  • test/unit/math/laplace/laplace_solver_fallback_test.cpp (new), with a likelihood that solver 1 rejects and solver 2 handles: a null stream must not throw (it did); with fallthrough disabled the call must throw with a reason, also after an earlier logged fallback in the same process (it ended in "solver not valid"); a stream receives the warning.
  • The existing Laplace tests are unchanged.

Side Effects

  • Solver 1 now succeeds on rank-deficient blocks where it previously fell through to solver 2; results agree to the solver tolerance.
  • The block_matrix_sqrt and disabled-fallthrough error messages change; nothing matches on the old texts. internal::log_solver_fallback loses its allow_fallthrough parameter.

Release notes

Embedded Laplace approximation: solver 1 no longer fails on rank-deficient block Hessians, a null message stream no longer turns an allowed solver fallback into an error, and a solver failure with allow_fallthrough disabled is always reported with its reason.

Checklist

  • Copyright holder: Jachym Barvinek

    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

Jachym.Barvinek and others added 3 commits September 26, 2026 18:03
block_matrix_sqrt used RealSchur and rejected any negative entry on the
Schur diagonal. The block is a negative Hessian of a log-concave
likelihood: symmetric positive semi-definite, and rank deficient whenever
there are more latent variables than observations (common with a dense
coefficient block). Its zero eigenvalues come out of floating point with
either sign, so solver 1 failed on every such call and fell back to
solver 2 after computing one Hessian for nothing.

Symmetrise the block, use SelfAdjointEigenSolver, clamp eigenvalues that
are negative only at rounding level and reject a block with a genuinely
negative eigenvalue. The non-finite check also only fired when no entry
was finite; it now fires when any entry is not.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
log_solver_fallback threw whenever the message stream was null, even with
allow_fallthrough set, so callers without a stream lost the fallback
entirely. And since the call sits inside std::call_once, a failure with
allow_fallthrough unset after an earlier logged fallback was not reported
at all and ended in a misleading "solver not valid" error.

Decide first: throw with the failing solver's reason when fallthrough is
disabled, otherwise log the fallback once if a stream is available.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@SteveBronder

Copy link
Copy Markdown
Collaborator

This is cool! Another cool update would be to use Eigen's BlockSparseMatrix for the block diagonal we use here

Comment thread stan/math/mix/functor/laplace_marginal_density_estimator.hpp Outdated
Co-authored-by: Steve Bronder <Stevo15025@gmail.com>
@jachymb

jachymb commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

@SteveBronder BlockSparseMatrix is officially unsupported in Eigen 5, so I think including it may be too clunky/risky.

…tive tolerance

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@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.23 0.23 1.0 -0.06% slower
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 1.05 4.53% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 0.93 -7.02% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.71 0.71 1.0 0.14% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.2 3.2 1.0 -0.08% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 42.89 42.51 1.01 0.88% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.6 0.6 0.99 -0.97% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.53 4.52 1.0 0.27% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 20.87 20.88 1.0 -0.05% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.89 0.89 1.0 0.29% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.0 -0.01% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 8.57 8.51 1.01 0.69% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.38 6.34 1.01 0.57% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 165.53 165.7 1.0 -0.1% slower
performance.compilation 396.5 396.93 1.0 -0.11% slower
Mean result: 0.9997841993394665

Jenkins Console Log
Jenkins Build Stages
Commit hash: 41a5a9b9e7d9963091a42eb85eef0571afbb0cab

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:                                 1495.989
CPU max MHz:                             3416.0681
CPU min MHz:                             1500.0000
BogoMIPS:                                4491.56
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

@SteveBronder

Copy link
Copy Markdown
Collaborator

Oh shoot it is still in unsupported in 5.0. They moved / fixed it on their main branch but it must have been post release

…ce. Hides throwing conditionals behind cold compiler hint macro

@SteveBronder SteveBronder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm! I made a few small cleanups for the conditional statements that throw and I think this is good to merge when tests pass

@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.23 0.22 1.01 0.66% faster
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 1.0 0.35% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.33 6.31 1.0 0.27% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 0.97 -3.13% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 8.45 8.45 1.0 0.02% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.5 4.47 1.01 0.84% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 166.03 166.09 1.0 -0.04% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.89 0.88 1.01 0.53% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.71 0.7 1.02 1.92% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 42.87 42.45 1.01 1.0% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.6 0.6 1.0 -0.21% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 20.98 20.92 1.0 0.29% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 0.96 -4.09% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.21 3.19 1.01 0.61% faster
performance.compilation 377.13 382.95 0.98 -1.54% slower
Mean result: 0.9985492689031078

Jenkins Console Log
Jenkins Build Stages
Commit hash: 01b1101563e8fdf876d079e7782431006076434c

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.317
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

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants