Repository navigation
Conversation
The central differences of the gradient were multiplied by epsilon / 2 instead of 1 / (2 epsilon), so the Hessian was 1e-6 times too small and each Newton step 1e6 times too long. newton_step then halved the step about 20 times per iteration, and on Gaussian-process models with an embedded Laplace approximation it ran to parameters where the log density is +inf.
|
Excellent work! Crazy this wasn't spotted bewfore Claude suggested additional test: The new test has one parameter, so it checks only the diagonal. A test with two parameters also checks the off-diagonal elements and the symmetrization. The existing test model #include <stan/model/grad_hess_log_prob.hpp>
#include <stan/io/empty_var_context.hpp>
#include <test/test-models/good/optimization/rosenbrock.hpp>
#include <gtest/gtest.h>
TEST(ModelUtil, grad_hess_log_prob_2d_values) {
// log density -((1 - x)^2 + 100 (y - x^2)^2) at (x, y) = (0.5, 1):
// gradient (151, -150), Hessian [[98, 200], [200, -200]]. The gradient is
// a cubic polynomial, so the 4-point differences are exact up to rounding.
// The off-diagonal elements check the symmetrized cross terms.
stan::io::empty_var_context data_var_context;
stan_model model(data_var_context, 0, static_cast<std::stringstream*>(0));
std::vector<double> params_r{0.5, 1.0};
std::vector<int> params_i;
std::vector<double> gradient, hessian;
double lp = stan::model::grad_hess_log_prob<true, true, stan_model>(
model, params_r, params_i, gradient, hessian, 0);
EXPECT_FLOAT_EQ(-56.5, lp);
ASSERT_EQ(2, gradient.size());
EXPECT_FLOAT_EQ(151, gradient[0]);
EXPECT_FLOAT_EQ(-150, gradient[1]);
ASSERT_EQ(4, hessian.size());
EXPECT_NEAR(98, hessian[0], 1e-8);
EXPECT_NEAR(200, hessian[1], 1e-8);
EXPECT_NEAR(200, hessian[2], 1e-8);
EXPECT_NEAR(-200, hessian[3], 1e-8);
}I compiled this test with googletest 1.11.0 against the develop header and against your header, outside the stan test framework (the model header generated with stanc 2.40.0). With develop, all 4 Hessian elements fail (98e-6, 200e-6, 200e-6, -200e-6). With your header the test passes; the errors are 0.9e-11 to 2.0e-11 at -O0 and -O3, so the tolerance 1e-8 has a margin of about 500. On the interaction with stan-dev/math#3469: |
Jenkins Console Log Machine informationDistributor 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: 1497.887 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 |
AI use disclosure: This was developed with the help of Claude Code (Opus 5.5).
Submission Checklist
./runTests.py src/test/unitmake cpplintSummary
stan::model::grad_hess_log_probestimates the Hessian from gradients atThe coefficients were multiplied by$\varepsilon/2$ instead of $1/(2\varepsilon)$ , so the Hessian came out $\varepsilon^2 = 10^{-6}$ times too small. The only caller in Stan is $-H^{-1}g$ was $10^6$ times too long. $+\infty$ far from the mode (embedded Laplace with a numerically singular covariance, part 2 of stan-dev/math#3469), that first step can land there.
optimization::newton_step, so its Newton stepnewton_stephalves the step until the log density does not decrease, which took about 20 halvings (one gradient evaluation each) per iteration, and accepted the first step that did not lower it. On models where Stan Math wrongly returns a log density ofOpen PR #3429 changes
newton_stepto compute its Hessian withstan::math::internal::finite_diff_hessian_auto, which also avoids this bug for the Newton optimizer. This PR fixesgrad_hess_log_probitself, which is public API, and it fixes Newton until #3429 is merged. The two PRs touch different files.For discussion
Consider deprecating$10^6$ times too small since v2.13.0 (2016) without a report. The alternatives are $10^6$ times too small.
grad_hess_log_probonce #3429 is in. After #3429 nothing in Stan calls it. A GitHub code search finds no other caller apart from vendored copies of the Stan headers and two options of rstan's unexporteddoctor_cppcode, which rstan does not use. Its Hessian has beenstan::model::hessian(nested autodiff, withproptoandjacobianfixed to true) and Stan Math's internalfinite_diff_hessian_auto, whichlaplace_samplealready uses;grad_hess_log_probcould also stay as a thin wrapper over the latter. Either way, until it is removed, this fix keeps it from returning a HessianIntended Effect
grad_hess_log_probreturns the Hessian, and the Newton optimizer needs about a tenth of the gradient evaluations. Against develop,algorithm=newtonwithiter=100on 7 GLM-type models × 20 seeds and 5 embedded-Laplace models × 5 seeds: 0.06–0.15 times develop's mean evaluations per model (geometric mean 0.09), and all 165 runs end at the best log density found, against 137 on develop. Develop hits the iteration limit in 42 runs and ends at a log density ofHow to Verify
ModelUtil.grad_hess_log_prob_values(src/test/unit/model/grad_hess_log_prob_test.cpp): log densityModelUtil.grad_hess_log_probandsrc/test/unit/services/optimize/newton_test.cpp,newton_jacobian_test.cpp.Side Effects
Measured with an in-process A/B harness against develop (gradient evaluation counts, platform independent); I can share the harness. Newton iterates change. On the GLM-type models the runs end closer to the mode (median distance to the best log density$10^{-12}$ instead of $4 \cdot 10^{-8}$ ).
grad_hess_log_probhas no other caller in Stan.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: