Skip to content

Optimizer: update the dense BFGS inverse Hessian in O(n²) instead of O(n³) - #3443

Open
jachymb wants to merge 2 commits into
stan-dev:developfrom
jachymb:feature/bfgs-update-rank-two
Open

jachymb wants to merge 2 commits into
stan-dev:developfrom
jachymb:feature/bfgs-update-rank-two

Conversation

@jachymb

@jachymb jachymb commented Oct 18, 2026 •

Copy link
Copy Markdown

This is a big one. Not in terms of LOC, but in terms of consequences.

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

Submission Checklist

  • Run unit tests: ./runTests.py src/test/unit
  • Run cpplint: make cpplint
  • Declare copyright holder and open-source license: see below

Summary

BFGSUpdate_HInv::update (src/stan/optimization/bfgs_update.hpp, the inverse Hessian of algorithm=bfgs) computed

$$H \leftarrow (I - \rho s y^\top) H (I - \rho y s^\top) + \rho s s^\top, \qquad \rho = 1 / s^\top y,$$

with two $n \times n$ by $n \times n$ matrix products. Expanding the product with $u = H y$ and $H = H^\top$ gives the same matrix as a rank-two update,

$$H \leftarrow H + (c s - \rho u) s^\top - \rho s u^\top, \qquad c = \rho^2 y^\top u + \rho,$$

which costs one matrix-vector product and two outer-product updates, $O(n^2)$ instead of $O(n^3)$. At a reset, $H = (s^\top y / y^\top y) I$ is set first and updated the same way, as before. The work vectors $u$ and $c s - \rho u$ are members, so the update allocates nothing.

Intended Effect

Less time per dense BFGS iteration, growing with the number of parameters: by construction. Measured in process against develop's update (-O3 -DNDEBUG, 3 runs of 11 interleaved rounds, pairs from a quadratic), branch / develop time per update:

$n$ 10 50 100 200 500
WSL2, g++ 12.2 0.16–0.18 0.05–0.07 0.022–0.024 0.012–0.016 0.009–0.010
MSYS2 MinGW-w64, g++ 15.2 0.12–0.13 0.034–0.035 0.015–0.016 0.010–0.012 0.007

The search directions agree with develop's to $10^{-15}$ relative.

How to Verify

The change keeps the values up to rounding, so no test fails on develop, and it adds none. Existing tests that reach the changed code pass unchanged: bfgs_update_test.cpp, bfgs_minimizer_test.cpp, bfgs_test.cpp, bfgs_exponential_boundary_test.cpp and services/optimize/{bfgs,bfgs_jacobian}_test.cpp; ServicesOptimize.rosenbrock in services/optimize/bfgs_test.cpp pins the dense BFGS trajectory (number of iterates, final point).

Side Effects

Measured with an in-process A/B harness against develop on 20 model configurations (GLMs, a hierarchical logistic regression, embedded-Laplace GLMMs and GPs; 900 dense BFGS runs per setting); I can share the harness. At CmdStan's defaults every run takes the same iterations and gradient evaluations as on develop, and the final log density agrees to $1.1 \cdot 10^{-9}$ relative. With tol_rel_obj = tol_rel_grad = 1, where runs end at the precision limit, rounding changes where 325 runs stop: evaluations 1.01 times develop's (geometric mean; per configuration 0.80–1.24), 795 of the 900 runs end at the best log density, as on develop, and line-search failures go from 296 to 302 (118 runs switch between OK and a line-search failure). The update allocates nothing per call.

Documentation

None.

Copyright and Licensing

Please list the copyright holder for the work you are submitting (this will be you or your assignee, such as a university or company):

Jáchym Barvínek jachymb@gmail.com

By submitting this pull request, the copyright holder is agreeing to license the submitted work under the following licenses:

BFGSUpdate_HInv::update formed (I - rho s y') H (I - rho y s') + rho s s'
with two n x n matrix products. Expanded with u = H y it is the rank-two
update H + (c s - rho u) s' - rho s u', c = rho^2 y'u + rho.
@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.98 -1.64% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.16 1.0 -0.45% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.87 0.86 1.01 0.9% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.97 -3.45% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.1 0.1 0.99 -1.04% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.16 8.11 1.01 0.57% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.64 3.69 0.98 -1.53% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.68 32.31 1.01 1.13% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.39 0.99 -0.57% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.81 6.79 1.0 0.34% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 166.02 163.65 1.01 1.43% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.16 3.24 0.98 -2.5% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.61 0.61 0.99 -0.75% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.81 25.7 1.0 0.44% faster
performance.compilation 395.98 350.68 1.13 11.44% faster
Mean result: 1.00405679274823

Jenkins Console Log
Jenkins Build Stages
Commit hash: 6a335dd02ea35aac291d2cb571d03092a8b16ad7

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

@avehtari

avehtari commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Looks good

The update is a symmetric rank-2 update, H + s w' + w s' with w = (c / 2) s - rho u, so it can keep only the lower triangle: _Hk.selfadjointView<Eigen::Lower>().rankUpdate(s, w), with both matrix-vector products through the same view. I pushed this as one commit to your branch (bfgs_update.hpp only, +10/-7). rankUpdate copies plain vector arguments, so the commit passes Maps; with them neither update nor search_direction allocates. (-(_Hk * gk) in search_direction allocates a temporary, on develop and on this branch.)

Time per BFGS iteration (update plus search_direction), Xeon Gold 6248, g++ 14.3, -O3 -DNDEBUG, ratio of the medians of 7 interleaved rounds:

n 10 30 100 300 1000
lower triangle / original PR 0.99 0.73 0.65 0.55 0.47

update alone is 0.42 to 0.87 times this PR's time. search_direction alone is slower up to n = 100 (1.14 to 1.41 times) and faster above (0.63 at n = 1000). The round-to-round spread of each ratio is at most 0.02, except 0.1 for search_direction at n = 300.

H is then also exactly symmetric. It agrees with this PR's H to within 3e-10 relative after 400 updates at condition number 1e14, closer than this PR agrees with develop (1.9e-8). The 7 suites that reach BFGSUpdate_HInv pass unchanged (55 tests, including ServicesOptimize.rosenbrock).

@jachymb

jachymb commented Oct 19, 2026

Copy link
Copy Markdown
Author

@avehtari Thanks! I also got the idea to only use triangle some time after creating the PR, but you were faster than me. Nicely done!

@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 8.74 8.32 1.05 4.76% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 2.19 2.22 0.99 -1.21% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.06 0.06 1.01 1.04% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 4.31 4.23 1.02 1.91% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.43 0.43 1.0 0.37% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 2.7 2.7 1.0 -0.06% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.26 0.25 1.07 6.43% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 19.83 19.92 1.0 -0.44% slower
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.02 0.02 0.99 -1.2% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.1 0.1 0.99 -0.89% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 91.28 93.98 0.97 -2.96% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 1.58 1.59 1.0 -0.21% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.05 4.32% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.28 0.28 1.02 1.52% faster
performance.compilation 256.02 253.69 1.01 0.91% faster
Mean result: 1.0102551964825868

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:                           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.559
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

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.

3 participants