Skip to content

Compute skew_normal_lcdf and skew_normal_lccdf without cancellation in the tails - #3443

Open
avehtari wants to merge 3 commits into
developfrom
stable-skew-normal-cdfs
Open

avehtari wants to merge 3 commits into
developfrom
stable-skew-normal-cdfs

Conversation

@avehtari

@avehtari avehtari commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Addresses the skew normal item of #3364.

This PR improves the accuracy and speed of skew_normal_lcdf and skew_normal_lccdf.

#3364 suggested deriving skew_normal_lcdf and skew_normal_lccdf from std_log_lcdf, but does not fit that pattern and the skew normal tail needs its own computation.

This PR was assisted by Claude

Summary

skew_normal_lcdf and skew_normal_lccdf computed the probability on the linear scale and then took the log, so the error of the log probability was about 1e-16 / P. On a grid of 2079 points (z = (y - mu) / sigma from -100 to 100, alpha from -1000 to 1000) both functions were accurate for log P >= -20, and from log P ≈ -31 on they returned wrong values (for example skew_normal_lcdf(-1 | 0, 1, 10) = -38.12, true -58.59), location and scale gradients that were exactly 0, NaN and -inf. References: mpmath at 40 digits, two independent integral representations of the tail probability without subtraction, which agree to 1e-37.

There were two causes:

  1. The cdf Phi(z) - 2 T(z, alpha) (T is Owen's T function) cancels on the short-tail side, z < 0, alpha > 0: the relative error is about 1e-16 exp((alpha z)^2 / 2). The lccdf has the mirror defect for z > 0, alpha < 0. The gradients also used 1 + erf(alpha z / sqrt(2)), which is 0 there.
  2. skew_normal_lccdf computed 1 - Phi(z) by subtraction: wrong from z = 8 for every alpha, and -inf from z = 9 for alpha <= 0 (at alpha = 0 the defect of Errors when right-censoring: bug in normal_lccdf? #2847).

Changes:

  • skew_normal_lccdf(y | mu, sigma, alpha) is computed as skew_normal_lcdf(-y | -mu, sigma, -alpha), because -X ~ SkewNormal(-mu, sigma, -alpha), as normal_lccdf does since Aligned normal_lccdf and std_normal_lccdf with the lcdf functions #3363. This removes cause 2 and the duplicated code, and every repair of the lcdf now also repairs the lccdf. The arguments are negated with minus(), which keeps a var_value<Eigen::Matrix> a matrix. The implementation is internal::skew_normal_lcdf_impl<func>, where func is the function name in error messages; the public signatures do not change.
  • skew_normal_lcdf uses three exact representations, so that no large cancellation remains:
    • the short tail, z < 0, alpha > 0, alpha |z| >= 2.5: log F = -z^2 (1 + alpha^2) / 2 - log(pi z^2 alpha (1 + alpha^2)) + log J, with J = int_0^inf exp(-w) / ((1 + w / d2) sqrt(1 + w / d1)) dw, d1 = (alpha z)^2 / 2, d2 = z^2 (1 + alpha^2) / 2. J lies in (0, 1] and is smooth; a 23-node Gauss-Laguerre rule gives it to 8e-15 at alpha |z| = 2.5 and to 2e-17 from alpha |z| = 3. The gradients are d/dz log F = |z| (1 + alpha^2) M(alpha |z|) / J with M(x) = sqrt(pi / 2) x erfcx(x / sqrt(2)), and d/dalpha log F = -z^2 alpha / J. Nothing underflows, so this branch also works below z = -38.5. The form follows from F = (1 / pi) int_alpha^inf exp(-z^2 (1 + t^2) / 2) / (1 + t^2) dt with w = z^2 (t^2 - alpha^2) / 2;
    • alpha > 1 otherwise: F = 2 T(alpha |z|, 1 / alpha) + Phi(alpha z) erf(z / sqrt(2)), from Owen's identity T(h, a) + T(a h, 1 / a) = Phi(h) / 2 + Phi(a h) / 2 - Phi(h) Phi(a h). For z >= 0 both terms are positive; for z < 0 the cancellation factor stays below about 30 for alpha >= 2, independent of alpha;
    • alpha <= 1 otherwise: Phi(z) - 2 T(z, alpha) as before; there the cancellation factor is at most about 200.
  • The gradients of the last two branches are computed as exp(log numerator - log F), because exp(-z^2 / 2) and exp(-z^2 (1 + alpha^2) / 2) can be subnormal or 0 where their ratio to the cdf is not. The function now loops over the elements, as normal_lcdf does.

Could not find any library that computes this tail with relative accuracy: Boost and SciPy use Phi - 2T, and the bivariate normal method of Komelj (2023) is accurate in absolute terms.

Worst relative error on the grid, tail side (P < 1/2), / number of gross failures (NaN, inf, an exact 0 where the true value is above 1e-8, or a relative error above 1e-3):

true log P before, lcdf value before, lccdf value this PR, value this PR, gradients
-20 to -30 3e-7 / 0 3e-6 / 0 3e-15 / 0 7e-14 / 0
-30 to -40 5e-4 / 2 7e-5 / 25 8e-15 / 0 3e-13 / 0
-40 to -100 1e-6 / 18 - / 87 of 87 9e-16 / 0 7e-14 / 0
-100 to -700 9e-8 / 51 - / 173 of 173 2e-15 / 0 4e-13 / 0

The lccdf of this PR has the same errors as its lcdf (mirror). On a second set of 1952 points around the switches, the short-tail branch is within 6e-16 (value) and 6e-15 (gradients), also below log P = -700.

Time per call (ns, Xeon E5-2680 v3, 4096 points per region, three interleaved rounds, spread at most 1 %); ratio = before / this PR (bigger is better):

region before, lcdf double ratio double (lcdf / lccdf) ratio var with gradient (lcdf / lccdf)
bulk (|z| < 2, |alpha| < 3) 1070 1.13 / 1.13 1.11 / 1.09
short tail (alpha |z| from 3 to 10) 910 3.13 / 3.04 2.74 / 2.57
alpha from 1.3 to 100, outside the short tail 990 1.55 / 1.55 1.47 / 1.44
|alpha| < 1 710 1.01 / 1.01 1.00 / 0.97

owens_t dominates the cost: the short-tail branch calls none, and the second branch calls it with 1 / alpha < 1, which Boost evaluates without its own reflection.

Limits that remain

  • For z < -38.5 with alpha < 0.065 (including alpha <= 0) the probability still underflows (log P < -700), as in normal_lcdf on develop.
  • In the alpha <= 1 branch the gradients keep errors up to about 5e-13 near alpha |z| = 2.5 at large |z|: the cancellation factor times the relative error of Owen's T and Phi there. The exp(log numerator - log F) form costs about |log F| * 1e-16 relative (at most 1.6e-13 at log P = -700).
  • Where the probability is close to 1, the log value has an absolute error up to 1e-16, as before.
  • skew_normal_cdf (linear scale) is not changed.

Tests

  • New test/unit/math/rev/prob/skew_normal_lcdf_test.cpp: the value and the four partials against mpmath references at 15 points (9 in the short tail, including z = -40 and alpha = 1e4; 3 with alpha > 1 and 3 with alpha <= 1 outside it), a vectorized call over the three branches, and infinite y; relative tolerance 1e-12.
  • New test/unit/math/rev/prob/skew_normal_lccdf_test.cpp: the upper tail (8 points, z from 8 to 35), the short tail of the lccdf (4 points), 3 bulk points, a vectorized call, and the function names in error messages. The row check of both files is in skew_normal_cdf_test_helpers.hpp.
  • With the develop headers, 2 of the 4 lccdf test cases of the first commit fail (47 expectations). With the lcdf header of the first commit (the reflection only), 3 of 5 lcdf cases (51 expectations) and 1 of 5 lccdf cases (20 expectations) of the final tests fail.
  • The generated tests of test/prob/skew_normal pass (145 314 cases in 156 binaries, including the var_value<Eigen::Matrix> cases).

Side Effects

At infinite y the partials are now 0. Before, they were NaN at y = -inf (0 / 0) and, for alpha = 0, at y = +inf.

Release notes

Improved the accuracy and speed of skew_normal_lcdf and skew_normal_lccdf.

Checklist

  • Copyright holder: Aalto University

    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

@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 -1.1% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.17 0.16 1.01 1.15% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.87 0.85 1.03 2.44% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.97 -2.67% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.1 1.01 1.15% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.08 8.0 1.01 0.95% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.9 3.78 1.03 3.06% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.71 32.21 1.02 1.51% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.38 1.0 0.25% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.93 6.95 1.0 -0.38% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 135.02 135.67 1.0 -0.48% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.23 3.23 1.0 -0.04% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.61 0.6 1.01 1.19% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.77 26.39 0.98 -2.4% slower
performance.compilation 365.47 403.36 0.91 -10.37% slower
Mean result: 0.9970895650076009

Jenkins Console Log
Jenkins Build Stages
Commit hash: 44a50912ff3f2e71023ea29a6f91adf7c6b1cf87

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.356
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 added the distributions Issues that deal with distribution functions: pdf, pmf, cdf label Oct 17, 2026
@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.21 7.74 1.06 5.63% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 2.14 2.03 1.06 5.43% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.06 0.05 1.05 5.15% faster
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 4.2 3.95 1.06 5.96% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.42 0.4 1.06 5.36% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 2.64 2.5 1.05 5.09% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.24 0.24 1.04 3.72% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 19.06 18.02 1.06 5.44% faster
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.02 0.02 1.04 4.01% faster
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.1 0.09 1.07 6.76% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 89.11 83.52 1.07 6.27% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 1.57 1.46 1.07 6.48% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.03 2.81% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.28 0.26 1.08 7.51% faster
performance.compilation 239.4 210.69 1.14 11.99% faster
Mean result: 1.0625417992922497

Jenkins Console Log
Jenkins Build Stages
Commit hash: f0fa1549624776581808289c9720367089c95ef9

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

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

distributions Issues that deal with distribution functions: pdf, pmf, cdf numerics Numerical issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants