Skip to content

Expanded numerical stability and performance for std_normal_lcdf, reused across distributions & functions - #3406

Open
andrjohns wants to merge 9 commits into
developfrom
normal-lcdf-opt
Open

andrjohns wants to merge 9 commits into
developfrom
normal-lcdf-opt

Conversation

@andrjohns

Copy link
Copy Markdown
Collaborator

Summary

This PR extracts the key value and gradient calculations from the std_normal_lcdf header into reusable functions that other normal-cdf-related functions can delegate to, removing a lot of duplicated/inconsistent implementations.

The value and gradient calculations are also updated to replace the taylor expansions with the Cody rational approximations (previously only used for the tail).

Two other bugs were found & fixed for var_value<Eigen::VectorXd> handling:

  • as_array_or_scalar() now returns an array unchanged instead of re-wrapping it
  • ref_type_if keeps an rvalue arena_matrix by value rather than referencing a dead temporary

The valid ranges of inputs (before over/underflow) across all functions are expanded:

function develop value branch value develop gradient branch gradient
normal_lcdf, std_normal_lcdf [-5e30, 38.5] [-1e154, 38.5] (-1e308, 38.6] (-1e308, 38.6]
normal_lccdf, std_normal_lccdf [-38.5, 5e30] [-38.5, 1e154] [-38.6, 1e308) [-38.6, 1e308)
normal_cdf, std_normal_cdf [-37.5, 8.24] [-38.5, 8.28] [-37.5, 38.6] [-38.5, 38.6]
Phi [-37.5, 8.24] [-38.5, 8.28] [-38.6, 38.6] [-38.6, 38.6]
lognormal_lcdf [-38.5, 8.28] [< -500, 38.5] [-38.5, 37.6] [< -500, 37.6]
lognormal_lccdf [-8.28, 38.5] [-38.5, > 500] [-38.6, 38.5] [-38.6, > 500]
lognormal_cdf [-38.5, 8.28] [-38.5, 8.28] [-27.2, 37.6] [-38.5, 37.6]
exp_mod_normal_lpdf [-37.5, 1e308) [-1e154, 1e308) [-37.5, 1e308) (-1e308, 1e308)
exp_mod_normal_lcdf [-7.2, 37.9] [-2e5, ~745] [-8.2, ~745] [-2e5, ~745]
exp_mod_normal_lccdf [-7.2, ~745] [-38.4, 1e308) [-8.2, ~745] [-38.6, 1e308)
exp_mod_normal_cdf [-7.2, 37.9] [-38.4, 37.9] [-8.2, ~745] [-38.4, ~745]
skew_normal_lpdf [-38.5, 1e154] [-1e154, 1e154] [-38.5, 1e308) [-5e307, 1e308)

While performance is either unchanged or significantly improved across inputs:

function min slowest case max fastest case
normal_lcdf 1.66x double, N = 100000 3.56x var_valueEigen::Matrix, N = 1000
normal_lccdf 1.75x fvar, N = 100000 3.71x var_value, N = 1000
normal_cdf 0.92x fvar, N = 100000 2.13x double, N = 1000
std_normal_lcdf 1.78x fvar, N = 100000 5.08x var_valueEigen::Matrix, N = 1000
std_normal_lccdf 2.41x double, N = 100000 5.02x var_valueEigen::Matrix, N = 1000
std_normal_cdf 1.35x double, N = 100000 2.68x var_valueEigen::Matrix, N = 1000
Phi 1.17x fvar, N = 100000 1.65x double, N = 1000
lognormal_lcdf 1.37x var_value, N = 10000 2.60x double, N = 1000
lognormal_lccdf 1.32x fvar, N = 10000 2.43x double, N = 1000
lognormal_cdf 1.29x var_value, N = 10000 2.24x double, N = 1000
exp_mod_normal_lpdf 1.78x var_value, N = 10000 2.36x double, N = 1000
exp_mod_normal_lcdf 1.04x fvar, N = 100000 1.52x double, N = 1000
exp_mod_normal_lccdf 1.03x var_valueEigen::Matrix, N = 100000 1.51x double, N = 1000
exp_mod_normal_cdf 1.00x var_value, N = 100000 1.48x double, N = 1000
skew_normal_lpdf 1.58x var_value, N = 100000 2.49x double, N = 1000

Full timing comparisons

double (values only)

function N = 100 N = 1000 N = 10000 N = 100000
normal_lcdf 34.3 / 13.6 (2.52x) 34.5 / 13.4 (2.57x) 39.0 / 18.7 (2.08x) 40.0 / 24.2 (1.66x)
normal_lccdf 35.0 / 13.9 (2.52x) 34.8 / 13.6 (2.57x) 39.0 / 17.5 (2.24x) 40.2 / 19.4 (2.07x)
normal_cdf 28.3 / 13.7 (2.06x) 28.7 / 13.4 (2.13x) 28.4 / 16.9 (1.68x) 28.4 / 18.9 (1.50x)
std_normal_lcdf 36.3 / 14.3 (2.54x) 38.0 / 14.0 (2.71x) 39.8 / 17.8 (2.24x) 40.7 / 19.7 (2.06x)
std_normal_lccdf 36.8 / 13.4 (2.75x) 38.4 / 13.1 (2.93x) 39.9 / 15.4 (2.60x) 41.0 / 17.0 (2.41x)
std_normal_cdf 26.2 / 14.4 (1.82x) 26.8 / 14.1 (1.91x) 26.6 / 17.8 (1.50x) 26.6 / 19.7 (1.35x)
Phi 26.9 / 16.5 (1.64x) 27.2 / 16.5 (1.65x) 27.3 / 19.9 (1.37x) 27.2 / 20.8 (1.31x)
lognormal_lcdf 37.1 / 14.7 (2.53x) 36.8 / 14.1 (2.60x) 41.0 / 18.9 (2.17x) 42.8 / 20.8 (2.05x)
lognormal_lccdf 36.9 / 15.7 (2.36x) 36.7 / 15.1 (2.43x) 40.2 / 19.6 (2.05x) 42.3 / 21.6 (1.95x)
lognormal_cdf 32.0 / 15.3 (2.09x) 33.0 / 14.7 (2.24x) 36.1 / 19.2 (1.88x) 38.5 / 21.5 (1.79x)
exp_mod_normal_lpdf 29.3 / 13.4 (2.20x) 29.8 / 12.6 (2.36x) 31.1 / 14.6 (2.13x) 32.8 / 16.6 (1.97x)
exp_mod_normal_lcdf 57.5 / 38.5 (1.49x) 57.2 / 37.6 (1.52x) 57.7 / 49.9 (1.16x) 57.8 / 51.4 (1.12x)
exp_mod_normal_lccdf 57.6 / 38.8 (1.48x) 57.3 / 37.9 (1.51x) 57.6 / 50.6 (1.14x) 57.9 / 52.0 (1.11x)
exp_mod_normal_cdf 55.8 / 38.2 (1.46x) 55.6 / 37.4 (1.48x) 55.8 / 50.3 (1.11x) 56.0 / 51.8 (1.08x)
skew_normal_lpdf 30.9 / 12.9 (2.39x) 30.7 / 12.4 (2.49x) 33.2 / 17.0 (1.95x) 34.3 / 19.4 (1.77x)

var_value (Eigen::Matrix<var_value> y, var_value parameters, gradient)

function N = 100 N = 1000 N = 10000 N = 100000
normal_lcdf 62.2 / 18.6 (3.34x) 62.4 / 17.8 (3.50x) 70.1 / 29.5 (2.38x) 70.6 / 34.0 (2.08x)
normal_lccdf 67.2 / 18.7 (3.59x) 67.1 / 18.1 (3.71x) 73.6 / 21.4 (3.44x) 74.5 / 34.4 (2.16x)
normal_cdf 35.9 / 18.7 (1.92x) 36.1 / 17.9 (2.01x) 36.0 / 21.4 (1.69x) 36.1 / 22.9 (1.57x)
std_normal_lcdf 59.9 / 17.3 (3.47x) 61.5 / 17.2 (3.59x) 67.5 / 20.2 (3.34x) 68.2 / 21.6 (3.15x)
std_normal_lccdf 64.7 / 16.6 (3.89x) 66.1 / 16.4 (4.03x) 71.5 / 18.7 (3.83x) 72.0 / 20.2 (3.57x)
std_normal_cdf 32.2 / 18.3 (1.76x) 32.7 / 17.1 (1.91x) 32.7 / 20.1 (1.63x) 32.6 / 21.6 (1.51x)
Phi 37.8 / 26.3 (1.43x) 38.3 / 26.6 (1.44x) 38.5 / 31.4 (1.23x) 38.7 / 32.2 (1.20x)
lognormal_lcdf 32.5 / 20.7 (1.57x) 31.8 / 20.1 (1.58x) 34.6 / 25.2 (1.37x) 36.5 / 26.5 (1.38x)
lognormal_lccdf 32.5 / 21.2 (1.53x) 31.6 / 20.5 (1.54x) 33.9 / 25.6 (1.32x) 35.8 / 26.9 (1.33x)
lognormal_cdf 30.6 / 20.8 (1.47x) 29.9 / 20.2 (1.48x) 32.7 / 25.4 (1.29x) 34.6 / 26.7 (1.29x)
exp_mod_normal_lpdf 32.6 / 18.1 (1.80x) 32.5 / 17.2 (1.89x) 33.8 / 19.0 (1.78x) 35.6 / 20.0 (1.78x)
exp_mod_normal_lcdf 61.9 / 47.9 (1.29x) 61.4 / 46.1 (1.33x) 61.2 / 58.0 (1.06x) 61.8 / 59.5 (1.04x)
exp_mod_normal_lccdf 62.0 / 48.2 (1.29x) 61.3 / 47.3 (1.30x) 61.0 / 58.7 (1.04x) 62.1 / 60.0 (1.04x)
exp_mod_normal_cdf 60.0 / 48.1 (1.25x) 59.7 / 45.9 (1.30x) 59.4 / 57.9 (1.03x) 59.6 / 59.6 (1.00x)
skew_normal_lpdf 34.7 / 18.1 (1.92x) 34.3 / 17.4 (1.97x) 36.9 / 22.8 (1.62x) 38.5 / 24.4 (1.58x)

var_valueEigen::Matrix (var_valueEigen::VectorXd y, var_value parameters, gradient)

function N = 100 N = 1000 N = 10000 N = 100000
normal_lcdf 60.0 / 17.7 (3.39x) 60.1 / 16.9 (3.56x) 67.1 / 21.7 (3.10x) 67.9 / 33.0 (2.06x)
normal_lccdf 61.9 / 17.8 (3.48x) 61.3 / 17.1 (3.59x) 68.1 / 20.4 (3.35x) 68.9 / 33.3 (2.07x)
normal_cdf 35.0 / 17.8 (1.97x) 35.2 / 16.9 (2.08x) 35.2 / 20.3 (1.73x) 35.2 / 21.8 (1.61x)
std_normal_lcdf 59.0 / 12.1 (4.87x) 60.4 / 11.9 (5.08x) 65.9 / 15.3 (4.30x) 66.6 / 16.9 (3.95x)
std_normal_lccdf 60.2 / 12.5 (4.82x) 60.9 / 12.1 (5.02x) 66.1 / 15.1 (4.38x) 66.9 / 17.0 (3.94x)
std_normal_cdf 31.4 / 12.1 (2.59x) 31.8 / 11.9 (2.68x) 31.6 / 15.3 (2.06x) 31.8 / 16.9 (1.88x)
Phi 29.0 / 18.3 (1.59x) 28.9 / 18.1 (1.59x) 28.9 / 21.4 (1.35x) 29.1 / 22.5 (1.29x)
lognormal_lcdf 32.1 / 19.9 (1.61x) 31.1 / 19.1 (1.63x) 33.6 / 24.1 (1.39x) 35.4 / 25.5 (1.39x)
lognormal_lccdf 31.5 / 20.4 (1.54x) 30.6 / 19.3 (1.58x) 32.7 / 24.6 (1.33x) 34.5 / 25.9 (1.33x)
lognormal_cdf 29.8 / 19.9 (1.50x) 28.9 / 19.1 (1.51x) 31.5 / 24.3 (1.29x) 33.4 / 25.6 (1.31x)
exp_mod_normal_lpdf 31.8 / 17.3 (1.84x) 31.5 / 16.2 (1.95x) 32.7 / 18.0 (1.82x) 34.6 / 19.1 (1.81x)
exp_mod_normal_lcdf 60.8 / 46.9 (1.30x) 60.2 / 45.0 (1.34x) 60.1 / 56.9 (1.06x) 61.1 / 58.7 (1.04x)
exp_mod_normal_lccdf 60.8 / 47.1 (1.29x) 60.0 / 46.3 (1.29x) 60.0 / 57.7 (1.04x) 60.9 / 59.2 (1.03x)
exp_mod_normal_cdf 59.1 / 47.4 (1.25x) 58.4 / 45.1 (1.30x) 58.4 / 56.9 (1.03x) 59.2 / 58.5 (1.01x)
skew_normal_lpdf 34.1 / 17.2 (1.99x) 33.6 / 16.5 (2.03x) 36.0 / 21.8 (1.65x) 37.4 / 23.5 (1.59x)

fvar (tangent)

function N = 100 N = 1000 N = 10000 N = 100000
normal_lcdf 60.4 / 18.1 (3.33x) 60.7 / 17.5 (3.47x) 75.4 / 36.9 (2.04x) 79.0 / 45.4 (1.74x)
normal_lccdf 62.4 / 18.9 (3.30x) 61.7 / 17.9 (3.44x) 68.4 / 21.4 (3.20x) 80.5 / 46.0 (1.75x)
normal_cdf 36.3 / 18.7 (1.94x) 35.8 / 17.7 (2.02x) 36.0 / 21.1 (1.70x) 36.5 / 39.6 (0.92x)
std_normal_lcdf 60.4 / 17.4 (3.47x) 61.4 / 17.1 (3.59x) 67.3 / 20.0 (3.36x) 68.1 / 38.3 (1.78x)
std_normal_lccdf 61.7 / 17.0 (3.64x) 61.7 / 16.3 (3.78x) 67.0 / 18.6 (3.60x) 68.1 / 20.2 (3.37x)
std_normal_cdf 32.5 / 17.6 (1.85x) 32.5 / 17.1 (1.90x) 32.6 / 20.0 (1.62x) 33.0 / 21.6 (1.53x)
Phi 32.6 / 24.1 (1.35x) 32.8 / 24.5 (1.34x) 33.0 / 27.6 (1.20x) 33.1 / 28.3 (1.17x)
lognormal_lcdf 32.8 / 20.8 (1.58x) 31.6 / 19.8 (1.59x) 34.5 / 25.0 (1.38x) 36.3 / 26.2 (1.39x)
lognormal_lccdf 32.4 / 21.3 (1.52x) 31.3 / 20.1 (1.56x) 33.7 / 25.5 (1.32x) 35.8 / 26.7 (1.34x)
lognormal_cdf 30.8 / 20.6 (1.49x) 29.6 / 19.9 (1.48x) 32.5 / 25.2 (1.29x) 34.5 / 26.5 (1.30x)
exp_mod_normal_lpdf 33.2 / 18.0 (1.85x) 32.7 / 16.8 (1.94x) 34.2 / 18.9 (1.80x) 35.9 / 19.9 (1.80x)
exp_mod_normal_lcdf 61.8 / 47.6 (1.30x) 60.4 / 45.8 (1.32x) 61.1 / 57.8 (1.06x) 62.2 / 60.0 (1.04x)
exp_mod_normal_lccdf 61.9 / 47.8 (1.29x) 60.3 / 46.9 (1.28x) 61.2 / 58.7 (1.04x) 61.9 / 59.9 (1.03x)
exp_mod_normal_cdf 60.1 / 47.8 (1.26x) 58.7 / 45.7 (1.29x) 59.4 / 57.8 (1.03x) 60.6 / 60.1 (1.01x)
skew_normal_lpdf 35.1 / 18.0 (1.95x) 34.1 / 17.2 (1.98x) 37.0 / 23.1 (1.60x) 38.6 / 24.0 (1.61x)

Tests

Additional tests exercising the increased numerical stability are added, as well new mix tests for the distributions

Side Effects

N/A

Release notes

Increased numerical stability and performance of the normal, std_normal, lognormal and exp_mod_normal (LC)CDF functions

Checklist

  • Copyright holder: (fill in copyright holder information)

    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

@andrjohns

Copy link
Copy Markdown
Collaborator Author

This duplicates a bunch of the implementation over in #3405, so will make some suggestions/comments on that one and then rebase this once that PR lands

@avehtari

Copy link
Copy Markdown
Member

I guess we should coordinate more as I also was preparing PR for std_normal and normal

@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 -2.01% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.17 1.0 -0.23% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.86 0.88 0.98 -2.07% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 1.01 1.25% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.1 1.05 4.43% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.32 8.31 1.0 0.12% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.69 3.71 1.0 -0.34% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 33.64 33.02 1.02 1.83% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.38 0.99 -0.85% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.86 6.86 1.0 0.12% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 133.47 135.53 0.98 -1.54% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.21 3.2 1.0 0.45% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.6 0.59 1.01 1.07% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.27 25.0 1.01 1.07% faster
performance.compilation 393.17 392.02 1.0 0.29% faster
Mean result: 1.0026527691698786

Jenkins Console Log
Jenkins Build Stages
Commit hash: 98c64f32efad1c4821e30c9f76801a0d0c89d086

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

I reviewed this PR (with help from Claude). Looks great

Accuracy against mpmath

Worst ulp over 601 points per range:

range value gradient
deep tail [-300, -40] 1.69 0.85
[-40, -10] 1.51 0.87
[-10, -5.66] 1.60 0.85
seam [-5.8, -5.5] 1.54 3.12
[-5.66, -1] 1.71 5.92
seam [-0.7, -0.6] 2.37 2.75
near zero [-0.6, 0.6] 1.86 2.36
[0.6, 4] 7.25 4.81
[4, 10] 30.37 31.53

For comparison, develop's worst in-range relative error is 7.6e-06 to 5.6e-05, which is 3.4e+10 to 2.5e+11 ulp, across every branch except the far Mills tail. So this PR improves the gradient by about ten orders of magnitude.

One suggestion: recover the rounding error of z*z on the positive branch

exp(-(0.5 * x) * x) inherits a relative error of about eps * z^2 / 2 from its argument, which grows quadratically and is the dominant error above z = 4. Recovering the rounding error of z * z with fma and folding it back removes it:

const double h = z * z;
const double err = std::fma(z, z, -h);   // exact rounding error of z * z
const double density = exp(-0.5 * h) * (1.0 - 0.5 * err);

-0.5 * h is exact, since 0.5 is a power of two. Measured, worst ulp over 401 points per range:

range value now value with fma gradient now gradient with fma
[0.6, 4] 6.7 4.8 4.8 2.2
[4, 10] 30.1 3.5 30.3 2.6
[10, 20] 115.2 2.8 120.9 2.7
[20, 37] 494.4 3.1 503.2 2.2

The cost is 3 to 4 percent on a Xeon E5-2680 v3 and 2 to 5 percent on a Tesla V100, measured with the value and gradient computed together.

Two notes on this. It stays applicable after the rebase onto #3405, because it concerns the exp(-z^2/2) factor and not erfcx.

The same expression appears in std_normal_lcdf_impl in the OpenCL device function, so the change belongs in both places.

erfcx looks slightly faster on the lower tail

Beyond removing the duplicated Cody coefficients, #3405 may improve speed. Comparing your internal std_normal_erfcx path against calling erfcx directly, value and gradient computed together:

range (scaled) CPU GPU
far tail [-40, -10] 1.16 1.35
Cody [-10, -4] 1.10 2.21
Cody edge [-4, -2.5] 1.06 1.03
interior [-2.5, -0.1] 1.11 1.93

Ratios above 1 mean the direct erfcx call is faster.

@spinkney

Copy link
Copy Markdown
Member

awesome! thanks @andrjohns for putting this together, it's much needed

@avehtari

Copy link
Copy Markdown
Member

Two more functions get the benefit with no extra work

Two functions that benefit from this std_normal_lcdf PR that are missing from the PR text are

function calls OpenCL version
ordered_probit_lpmf std_normal_lcdf x4 none
von_mises_cdf normal_cdf none

One function benefits from erfcx directly and is not covered here

wiener4_lcdf_unnorm line 128 is:

return std_normal_lcdf(-x) - std_normal_lpdf(x);

It calls std_normal_lcdf, so it looks like it inherits the repair., but doesn't. That expression is the log Mills ratio, and both terms approach -x^2/2 while their difference stays O(log x), so the subtraction cancels no matter how accurate the inputs are. Assuming both inputs are already correctly rounded, which is the best case after this PR:

x log Phi(-x) log phi(x) result as a difference via erfcx
10 -53.2 -50.9 -2.3123 4.6 ulp 0.4 ulp
30 -454.3 -450.9 -3.4023 74.0 ulp 0.0 ulp
100 -5005.5 -5000.9 -4.6053 195.7 ulp 0.3 ulp
300 -45006.6 -45000.9 -5.7038 6132.2 ulp 0.2 ulp

The loss grows without bound. log Phi(-x) - log phi(x) equals log(sqrt(pi/2) * erfcx(x * INV_SQRT_TWO)) exactly, so one erfcx call removes the subtraction. Out of scope for this PR, but worth recording as the one which calls std_normal_lcdf but not benefiting from this PR.

@SteveBronder

SteveBronder commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

@andrjohns this is very cool! Because of how tied in this and #3405 are do you want to handle the #3405 review and then I'll review this once that is in?

@andrjohns

Copy link
Copy Markdown
Collaborator Author

@andrjohns this is very cool! Because of how tied in this and #3405 are do you want to handle the #3405 review and then I'll review this once that is in?

Yep sounds like a plan to me!

@SteveBronder

Copy link
Copy Markdown
Collaborator

@andrjohns ping me when this is ready for review

@SteveBronder

Copy link
Copy Markdown
Collaborator

@andrjohns is this ready for me to look at?

@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.31% faster
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.06 0.06 0.96 -4.44% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 6.32 6.31 1.0 0.13% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.02 0.02 0.98 -2.0% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 8.45 8.43 1.0 0.23% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 4.49 4.46 1.01 0.69% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 165.47 165.13 1.0 0.2% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.89 0.89 1.0 -0.08% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.7 0.71 0.99 -0.92% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 42.53 42.72 1.0 -0.45% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.6 0.6 0.99 -0.74% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 21.08 20.78 1.01 1.43% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.0 -0.4% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.19 3.19 1.0 0.22% faster
performance.compilation 386.86 387.1 1.0 -0.06% slower
Mean result: 0.9969507030598858

Jenkins Console Log
Jenkins Build Stages
Commit hash: 1a419c76226745cd916ab56e54b60394f2ebbdff

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants