Skip to content

Do not pre-size Laplace matrices that are reassigned - #3464

Open
jachymb wants to merge 11 commits into
stan-dev:developfrom
jachymb:bugfix/laplace-arena-reallocation
Open

jachymb wants to merge 11 commits into
stan-dev:developfrom
jachymb:bugfix/laplace-arena-reallocation

Conversation

@jachymb

@jachymb jachymb commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

A relatively small fix that saves some wasted memory in embedded Laplace under some circumstances while simplifying the code a bit.

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

Summary

In the var overload of laplace_marginal_density, R was pre-sized n × n for solvers 1 and 2 and LU_solve_covariance n × n for solver 3, but only solver 1 writes into its buffer in place. Solvers 2 and 3 assign an expression, which maps the arena_matrix onto a newly allocated buffer, so the pre-sized one was never used: 8n² wasted arena bytes per gradient, which raise the arena's high-water mark for the rest of the run. Now R is pre-sized only for solver 1 and LU_solve_covariance is default-constructed.

Tests

test/unit/math/laplace/laplace_marginal_density_arena_test.cpp records the peak approx_bytes_used() of the arena at the likelihood calls of one gradient (Poisson GP, n = 50, allow_fallthrough off so that solver 3 really runs). It bounds solver 2 by solver 1 plus half an n × n matrix, and solver 3, which legitimately holds one more matrix (A), by solver 1 plus one and a half. It fails on develop, where solver 2 peaks 19,200 bytes above solver 1 and solver 3 39,200 above, and passes here (800 below and 19,200 above).

The Laplace tests that reach the changed overload pass at O=0 (WSL, g++ 12.2), without their dimension-500 and disease-map cases: laplace_marginal_lpdf_test, laplace_marginal_poisson_log_lpmf_test, laplace_marginal_neg_binomial_log_lpmf_test and laplace_marginal_neg_binomial_log_summary_lpmf_test.

Side Effects

One gradient with solver 2 or 3 uses 8n² fewer arena bytes; values are identical to develop. Timing of solver 2 against develop (in-process, -O3 -DNDEBUG, WSL g++ 12.2 and MSYS2 g++ 15.2, n = 20 to 400) is within noise, with medians of −0.35 % and −0.5 %; solver 3 was not benchmarked. Keeping the matrices on the arena rather than the heap measured 1.4 to 2 % faster for n ≥ 200.

Release notes

The gradient of the embedded Laplace approximation with solvers 2 and 3 uses less memory.

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

Jachym.Barvinek and others added 8 commits October 4, 2026 21:53
R was pre-sized for solvers 1 and 2 and LU_solve_covariance for solver
3, but solvers 2 and 3 assign them with `=`, which gives an arena_matrix
a new buffer; the pre-sized n x n buffers were never used. Pre-size R
only for solver 1, which writes it in place.
@SteveBronder

Copy link
Copy Markdown
Collaborator

Alternatively, could we just use R.noalias() in solvers 2 and 3?
Solver 2 does

R = md_est.W_r
          - md_est.W_r * md_est.K_root
                * md_est.L.transpose()
                      .template triangularView<Eigen::Upper>()
                      .solve(
                          md_est.L.template triangularView<Eigen::Lower>()
                              .solve(md_est.K_root.transpose() * md_est.W_r));

Solver 3 does

R = md_est.W_r * I_minus_BinvKW;

I have to check how this allocates, but I think it would reuse R's memory.

@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.01 1.04% faster
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 1.0 -0.09% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.36 6.37 1.0 -0.25% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 0.97 -3.49% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 8.29 8.34 0.99 -0.63% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.44 4.43 1.0 0.07% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 168.35 168.53 1.0 -0.11% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.89 0.89 1.0 -0.25% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.62 0.61 1.01 0.88% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 43.17 42.81 1.01 0.85% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.58 0.58 1.01 0.68% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 21.01 21.0 1.0 0.08% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 0.96 -4.46% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.18 3.21 0.99 -0.91% slower
performance.compilation 399.83 399.72 1.0 0.03% faster
Mean result: 0.9958642063000231

Jenkins Console Log
Jenkins Build Stages
Commit hash: 29e32c4215464fd5550540ce9a448016d22be56f

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

Ah, I didn't know about this option. It seems to make the intent of the code clearer.

@jachymb

jachymb commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

@SteveBronder
Thanks, I applied your approach with a little bit of adjustments (I think necessary to compile). It's not only clearer, but on top of my original saving, it spares us a n^2 eigen heap temporary and its copy per gradient in solvers 2 and 3 and I measured a small but consistent speed improvement for solver 3 (~1-3% in full gradient, given just by the R statement change).

@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.98 -1.85% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 4.18 4.25 0.98 -1.8% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 18.72 18.97 0.99 -1.33% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.24 0.24 0.99 -0.76% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 8.19 8.22 1.0 -0.36% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.1 0.1 0.96 -4.5% slower
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.02 0.02 0.93 -7.56% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.06 0.06 0.94 -6.65% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 2.66 2.65 1.0 0.29% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 1.54 1.54 1.0 -0.26% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 66.99 89.32 0.75 -33.32% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.42 0.43 0.97 -2.75% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 2.16 2.18 0.99 -1.03% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.28 0.28 0.98 -1.66% slower
performance.compilation 234.04 239.13 0.98 -2.18% slower
Mean result: 0.962672644273032

Jenkins Console Log
Jenkins Build Stages
Commit hash: 29e32c4215464fd5550540ce9a448016d22be56f

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.468
CPU max MHz:                             3900.0000
CPU min MHz:                             1000.0000
BogoMIPS:                                5000.00
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: VMX unsupported
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 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 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 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

Comment thread test/unit/math/laplace/laplace_marginal_density_arena_test.cpp Outdated
@SteveBronder

Copy link
Copy Markdown
Collaborator

Once the test is removed then this is good to go!

@jachymb

jachymb commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Removed the failure-reproducing test, see comment above.

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.

4 participants