Skip to content

Fix the Laplace covariance for solver 2 and after a solver fallthrough - #3436

Merged
SteveBronder merged 1 commit into
developfrom
bugfix/laplace-base-rng-solver-used
Oct 15, 2026
Merged

SteveBronder merged 1 commit into
developfrom
bugfix/laplace-base-rng-solver-used

Conversation

@avehtari

@avehtari avehtari commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

This was assisted by Claude

Summary

laplace_base_rng() (stan/math/mix/functor/laplace_base_rng.hpp) computes the covariance of the Laplace approximation. laplace_latent_rng(), laplace_latent_tol_rng(), laplace_latent_solve(), laplace_latent_solve_tol() and laplace_latent[_tol]_{bernoulli_logit,poisson_log,neg_binomial_2_log}_rng() return this covariance or sample from it. laplace_base_rng() selected the formula with options.solver, the solver that the user requested. But the content of md_est.W_r, md_est.L, md_est.K_root and md_est.LU depends on the solver that produced md_est, which is md_est.solver_used. laplace_marginal_density() already selects by md_est.solver_used.

This gave two errors:

  1. Solver 2 returned a wrong covariance. The branch options.solver == 1 || options.solver == 2 used the solver-1 formula Sigma = K - V^T V with V = L^-1 W_r K. This is correct for solver 1, where W_r = sqrt(W) and L L^T = I + W_r K W_r. Solver 2 (CholeskyKSolver) stores W_r = W and L L^T = B = I + K_root^T W K_root, so the result was K - K W B^-1 W K instead of K_root B^-1 K_root^T. The wrong matrix can be positive definite, and then there is no error message (example, case 1).

  2. After a solver fallthrough, the formula did not match the solver. With allow_fallthrough = 1, a failed solver 1 continues with solver 2, and a failed solver 2 continues with solver 3. The formula stayed the one for options.solver:

    • after a fallthrough to solver 2, the result was the wrong covariance of item 1. In the example it is not positive definite, so cholesky_decompose() throws;
    • after a fallthrough to solver 3, md_est.L is 0 x 0. The triangular solve fails an Eigen assertion (SolveTriangular.h:177), and the process aborts. Because this is not an exception, Stan cannot reject the draw, and all output is lost.

solver = 1 and allow_fallthrough = 1 are the defaults (stan/math/prim/fun/generate_laplace_options.hpp). So the functions without control arguments took this path whenever solver 1 failed, that is, when the negative Hessian of the log-likelihood was not positive definite at a Newton iterate. This happens for likelihoods that are not log-concave (example, case 2). The laplace_marginal* functions do not call laplace_base_rng() and were not affected.

I found this while using laplace_latent_solve_tol() to construct importance-sampling proposals for a nonlinear joint model with 4 latent variables per group. Its log-likelihood is not concave at the mode for about half of the groups.

Changes

In stan/math/mix/functor/laplace_base_rng.hpp:

  • The formula is selected with md_est.solver_used.
  • Solver 1: formula unchanged.
  • Solver 2: new formula Sigma = C^T C with C = L^-1 K_root^T, that is Sigma = K_root B^-1 K_root^T. This is the form that laplace_marginal_density() uses for solver 2.
  • Solver 3: formula unchanged.
  • The Cholesky factor, or the draw, is computed once after the three branches. This removes the two duplicated return blocks.

No other file in stan/ changes.

Example

Two latent variables with prior covariance K = [1 0.5; 0.5 2]:

  • Case 1: Gaussian likelihood normal_lpdf(y | theta, s), y = (0.3, -0.2), s = 2. The Laplace approximation is exact, with covariance (K^-1 + I / s^2)^-1.
  • Case 2: Cauchy likelihood student_t_lpdf(y | 1, theta, s), s = 0.5, (a) y = (4, -3) and (b) y = (2.5, -2). At the mode, W = -d^2/dtheta^2 log p(y | theta) has one negative entry (-0.104 and -0.353), while K^-1 + W is positive definite. The reference is the mode from optim() and the analytic W.

Covariance Sigma = L L^T returned by the call, [row 1; row 2], 4 decimals:

case call develop this PR
1 _tol, solver 1 or 3 [0.7731 0.2689; 0.2689 1.3109] same
1 _tol, solver 2 [0.9462 0.4442; 0.4442 1.8226] [0.7731 0.2689; 0.2689 1.3109]
2a _tol, solver 3 [0.9784 0.0564; 0.0564 0.2050] same
2a _tol, solver 1, fallthrough process aborts (Eigen assertion) [0.9784 0.0564; 0.0564 0.2050]
2a default options process aborts (Eigen assertion) same as the row above, to 1e-4
2b _tol, solver 3 [1.2855 0.0559; 0.0559 0.1547] same
2b _tol, solver 1, fallthrough exception cholesky_decompose: Matrix m is not positive definite [1.2855 0.0559; 0.0559 0.1547]
2b default options the same exception same as the row above, to 1e-4

The values in the column "this PR" are the closed-form covariances. For case 1 with solver 2, the develop value is exactly K - K W B^-1 W K with W = I / 4 and B = I + K_root^T W K_root. The default-options calls agree to about 1e-4 because of the default convergence tolerance.

Stan program
functions {
  real ll(vector theta, vector y, real s, int cauchy) {
    return cauchy ? student_t_lpdf(y | 1, theta, s) : normal_lpdf(y | theta, s);
  }
  matrix k_fun(matrix K) {
    return K;
  }
}
data {
  vector[2] y;
  real<lower=0> s;
  int<lower=0, upper=1> cauchy;
  matrix[2, 2] K;
  int<lower=0, upper=1> default_options;
  int<lower=1, upper=3> solver;
  int<lower=0, upper=1> fallthrough;
}
generated quantities {
  matrix[2, 2] Sigma;
  {
    tuple(vector[2], matrix[2, 2]) lap;
    if (default_options) {
      lap = laplace_latent_solve(ll, (y, s, cauchy), 2, k_fun, (K,));
    } else {
      lap = laplace_latent_solve_tol(
        ll, (y, s, cauchy), 2, k_fun, (K,),
        (rep_vector(0.0, 2), 1e-10, 100, solver, 100, fallthrough));
    }
    Sigma = multiply_lower_tri_self_transpose(lap.2);
  }
}
R code (cmdstanr)
library(cmdstanr)
mod <- cmdstan_model("laplace_solver.stan")
K <- matrix(c(1, 0.5, 0.5, 2), 2)
lap_sigma <- function(y, s, cauchy, solver = 1, fallthrough = 0,
                      default_options = 0) {
  fit <- mod$sample(data = list(y = y, s = s, cauchy = cauchy, K = K,
                                default_options = default_options,
                                solver = solver, fallthrough = fallthrough),
                    fixed_param = TRUE, chains = 1, iter_sampling = 1,
                    refresh = 0, sig_figs = 12)
  matrix(fit$draws("Sigma", format = "matrix"), 2, 2)
}

# Case 1: Gaussian likelihood
y <- c(0.3, -0.2); s <- 2
print(solve(solve(K) + diag(1 / s^2, 2)))       # exact
for (solver in 1:3) print(lap_sigma(y, s, 0, solver = solver))

# Case 2: Cauchy likelihood (not log-concave)
s <- 0.5
for (y in list(c(4, -3), c(2.5, -2))) {
  f <- function(th) sum(dt((y - th) / s, df = 1, log = TRUE)) -
    0.5 * sum(th * solve(K, th))
  th <- optim(c(0, 0), function(t) -f(t), method = "BFGS",
              control = list(reltol = 1e-15))$par
  r <- (y - th) / s
  W <- (2 / s^2) * (1 - r^2) / (1 + r^2)^2      # W[1] < 0
  print(solve(solve(K) + diag(W)))               # exact
  print(lap_sigma(y, s, 1, solver = 3))
  print(try(lap_sigma(y, s, 1, solver = 1, fallthrough = 1)))
  print(try(lap_sigma(y, s, 1, default_options = 1)))
}

Tests

Four new tests in test/unit/math/laplace/laplace_latent_solve_test.cpp. They use the two cases of the example and compare with closed forms:

  • laplace_latent_solve.all_solvers_match_closed_form_normal: case 1. For solvers 1, 2 and 3 and Hessian block sizes 1 and 2, the mean and L L^T must equal Sigma y / s^2 and Sigma = (K^-1 + I / s^2)^-1.
  • laplace_latent_solve.fallthrough_matches_closed_form_cauchy: case 2, with the Cauchy likelihood written with cauchy_lpdf(). The test asserts that W has a negative entry at the mode. Solver 1 and solver 2 with allow_fallthrough = 1 must give the mode of solver 3 and the covariance (K^-1 + W)^-1, with W computed analytically at the mode. In the example, the fallthrough ends in solver 3 for case 2a and in solver 2 for case 2b.
  • laplace_latent_solve.default_options_cauchy: the same check for laplace_latent_solve() without control arguments. The test tolerance is 1e-3, because the default convergence tolerance (1.49e-8 on the change of the objective) gives a mode error of order 1e-4.
  • laplace_latent_tol_rng.solver_2_draw_uses_laplace_covariance: case 1. With the same seed, the draw of laplace_latent_tol_rng() with solver 2 equals the draw of multi_normal_rng() with the exact mean and covariance.

Without the change in laplace_base_rng.hpp, all four tests fail:

  • the first test fails for solver 2, at both block sizes;
  • the second and third tests stop with the exception cholesky_decompose: Matrix m is not positive definite (case 2b comes first in the tests, so the assertion failure of case 2a does not occur);
  • the fourth test gets a different draw.

With the change, these tests pass. The existing tests in laplace_latent_solve_test.cpp, laplace_bernoulli_logit_rng_test.cpp, laplace_poisson_log_rng_test.cpp, laplace_neg_binomial_2_log_rng_test.cpp and laplace_solver_fallback_test.cpp also pass. The current tests did not cover these cases: laplace_latent_solve_test.cpp used only solver 1, and laplace_solver_fallback_test.cpp uses only laplace_marginal_tol().

Side Effects

Results change only where they were wrong: solver 2, and solver 1 or 2 when a fallthrough occurs. Solver 1 without a fallthrough and solver 3 give the same values as before. The laplace_marginal* functions do not change.

Release notes

Fixed the covariance of the Laplace approximation in laplace_latent_rng(), laplace_latent_solve() and the related functions for solver 2 and after a solver fallthrough. Before this fix, the covariance was wrong, or the program stopped with an exception or a failed assertion. With the default options, a fallthrough occurs when the log-likelihood is not log-concave.

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

@avehtari
avehtari requested a review from SteveBronder October 9, 2026 08:58
@avehtari avehtari added the bug label Oct 9, 2026
@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 7.8 7.78 1.0 0.24% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 2.07 2.07 1.0 -0.04% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.05 0.05 1.02 2.2% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 3.94 3.92 1.0 0.39% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.4 0.4 1.0 -0.33% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 2.56 2.53 1.01 1.08% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.23 0.23 1.0 0.16% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 17.81 17.85 1.0 -0.24% slower
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.02 0.02 1.0 0.09% faster
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.09 0.09 1.01 0.89% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 62.51 63.15 0.99 -1.02% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 1.46 1.46 1.0 -0.12% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.99 -1.1% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.26 0.26 1.01 0.57% faster
performance.compilation 224.72 232.89 0.96 -3.63% slower
Mean result: 0.9995545244222791

Jenkins Console Log
Jenkins Build Stages
Commit hash: 44a50912ff3f2e71023ea29a6f91adf7c6b1cf87

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

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

Nice!

@SteveBronder
SteveBronder merged commit e4745c8 into develop Oct 15, 2026
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants