Skip to content

Optimizer: compute the CubicInterp roots without cancellation - #3446

Open
jachymb wants to merge 2 commits into
stan-dev:developfrom
jachymb:bugfix/cubic-interp-cancellation
Open

jachymb wants to merge 2 commits into
stan-dev:developfrom
jachymb:bugfix/cubic-interp-cancellation

Conversation

@jachymb

@jachymb jachymb commented Oct 18, 2026

Copy link
Copy Markdown

A relatively minor numerics improvement.

AI use disclosure: This was developed with the help of Claude Code (Opus 5.5, model ID claude-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

CubicInterp (src/stan/optimization/bfgs_linesearch.hpp) minimises the cubic $g(x) = c_3 x^3/6 + c_2 x^2/2 + c_1 x$ that interpolates the values and slopes at $0$ and $x_1$. It took the stationary points as

$$s_{1,2} = -\frac{c_2 \pm \sqrt{c_2^2 - 2 c_1 c_3}}{c_3}.$$

When the data are (nearly) quadratic, $c_3$ is rounding noise. For $c_2 > 0$ the numerator of $s_2$ then cancels, and $s_2$, the minimiser $\approx -c_1/c_2$, came out anywhere: CubicInterp returned an end of the interval ($10^{-12}$ instead of 0.1 for data from $\phi(x) = -x + x^2/0.2$ at $x_1 = 1$), or a point up to 28% off (0.128 at $x_1 = 0.4$). The roots are now computed as

$$q = c_2 + \mathrm{sign}(c_2) \sqrt{c_2^2 - 2 c_1 c_3}, \qquad s_1 = -\frac{q}{c_3}, \qquad s_2 = -\frac{2 c_1}{q},$$

the same two roots ($s_1 s_2 = 2 c_1 / c_3$), with no subtraction of nearly equal numbers. As $c_3 \to 0$, $s_1$ goes to $\pm\infty$ (outside the interval) and $s_2$ to $-c_1/c_2$.

BFGSMinimizer::step uses CubicInterp for the first trial step of every iteration after the first (except after a reset): 1.01 times the minimiser of the cubic along the previous step over $[\mathrm{minAlpha}, 1]$, capped at 1.

Intended Effect

CubicInterp returns the minimiser of the interpolating cubic for any data, including nearly quadratic data (typical near the optimum), where it returned an end of the interval or a point up to 28% off. BFGSMinimizer uses it for the first trial step of most iterations, so that step is again the cubic's estimate. When it was the lower end, $10^{-12}$, the line search spent about ten extra gradient evaluations expanding it tenfold at a time. Such iterations are rare in practice: on 20 model configurations (L-BFGS and dense BFGS, against develop) the evaluation counts stay at 0.99–1.00 times develop's, with as many runs reaching the best log density.

How to Verify

  • New test OptimizationBfgsLinesearch.CubicInterp_quadratic_data (src/test/unit/optimization/bfgs_linesearch_test.cpp): data at 0 and $x_1 = 0.4$ from $\phi(x) = -x + x^2/0.2$, minimised at 0.1, where $c_3 \approx -10^{-14}$ is rounding noise. It fails on develop, which returns 0.128.
  • Existing tests that reach the changed code pass unchanged: CubicInterp and CubicInterp_6arg in bfgs_linesearch_test.cpp, bfgs_minimizer_test.cpp, bfgs_test.cpp, bfgs_exponential_boundary_test.cpp, services/optimize/{bfgs,lbfgs,bfgs_jacobian,lbfgs_jacobian}_test.cpp and the Pathfinder tests services/pathfinder/{eight_schools,normal_glm}_test.cpp.

Side Effects

In-process A/B harness against develop (gradient evaluation counts, platform independent); I can share it. Behaviour changes:

  • Iterates of L-BFGS, BFGS and Pathfinder change wherever the first trial step changes. At CmdStan's defaults no configuration needs more than 5% more evaluations, and Pathfinder has the same failures, with every ELBO within 0.1 of develop's.
  • With tol_rel_obj = tol_rel_grad = 1, where runs end at the precision limit and small changes decide where they stop, some configurations need more evaluations (up to 1.20 times develop's for L-BFGS on a negative binomial regression, 1.15 for dense BFGS on a Laplace GP) and others fewer (down to 0.77).
  • Dense BFGS on test functions with only a gradient tolerance of $10^{-12}$: Beale needs 1.06 times develop's evaluations, and 2 more of 40 log-sum-exp runs end in a line-search failure.

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:

CubicInterp found the stationary points of the interpolating cubic as
-(c2 +- sqrt(c2^2 - 2 c1 c3)) / c3. For nearly quadratic data c3 is
rounding noise and one of the two roots cancels: CubicInterp returned an
end of the interval, or a point up to 28% off, instead of the minimiser.
The roots are now -q / c3 and -2 c1 / q with q = c2 + sign(c2) sqrt(...).
@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.99 -0.82% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.16 1.0 0.24% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.88 0.85 1.03 3.29% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.02 1.57% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.1 1.01 1.47% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.25 8.36 0.99 -1.32% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.74 3.68 1.02 1.79% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.62 33.1 0.99 -1.47% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.39 0.38 1.02 2.0% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.78 6.8 1.0 -0.26% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 167.09 163.93 1.02 1.89% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.21 3.22 1.0 -0.22% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.6 0.62 0.98 -1.99% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.81 26.26 0.98 -1.74% slower
performance.compilation 401.26 377.98 1.06 5.8% faster
Mean result: 1.0073222337664665

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

Copy link
Copy Markdown
Member

Your test relies on c3 being rounding noise of about -5.5e-14. FMA contraction or another compiler can change that value. Could you add the exact c3 = 0 case as well? Its result does not depend on the platform.

The existing test relies on c3 being rounding noise, whose value FMA
contraction or another compiler can change. Data from -x + x^2 at x1 = 1
make every coefficient exact and c3 = 0 on any platform; develop returned
the lower bound there, since the root was 0 / 0.
@jachymb

jachymb commented Oct 19, 2026

Copy link
Copy Markdown
Author

Fair point, added. Data from $\phi(x) = -x + x^2$ at $x_1 = 1$ gives CubicInterp(-1.0, 1.0, 0.0, 1.0, 1e-12, 1.0). Every coefficient is exact, so $c_3 = 0$ on any platform. On develop the root is $0/0$ and it returns the lower bound 1e-12; this branch returns 0.5.

One more note, on the other degenerate cases: with $c_3 = 0$, the new form gives $s_2 = -c_1/c_2$ exactly and $s_1 = \pm\infty$. $q = 0$ needs $c_2 = 0$ and $c_1 c_3 = 0$, and there each root is either correct or $\pm\infty$/NaN. Neither passes the open-interval check loX < s && s < hiX, which is the right result (no stationary point inside the interval), so I didn't add a separate guard. The only caller, BFGSMinimizer::step, passes $c_1 &lt; 0$ anyway.

@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 0.99 -0.95% slower
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 0.94 -5.94% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.33 6.34 1.0 -0.14% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 0.93 -7.62% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 8.25 8.29 1.0 -0.42% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.45 4.47 1.0 -0.3% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 217.66 220.93 0.99 -1.5% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.9 0.89 1.01 1.17% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.61 0.62 0.99 -0.72% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 42.47 42.61 1.0 -0.34% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.6 0.59 1.01 1.02% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 20.96 20.89 1.0 0.35% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.04 3.47% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.2 3.18 1.01 0.56% faster
performance.compilation 367.47 365.9 1.0 0.43% faster
Mean result: 0.9934234896265376

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

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