jax icon indicating copy to clipboard operation
jax copied to clipboard

`special.betainc`, `stdtr`, and `stdtrit` are very slow

Open crusaderky opened this issue 1 year ago • 4 comments

Description

Executive summary

  • jax.scipy.special.betainc on CPU is 10x slower than scipy.special.betainc running on a NumPy array (warm jit and large array, to make dispatch time negligible)
  • on GPU, it barely matches scipy's performance on CPU (for suitably large arrays)
  • This also impacts scipy.special.stdtr and scipy.special.stdtrit. These functions do not exist in jax.scipy, but they are implemented in scipy proper by dispatching to jax.scipy.special.betainc: https://github.com/scipy/scipy/blob/ad9ffdc83ed819ca0adbfceef5a435338f856c03/scipy/special/_support_alternative_backends.py#L149-L178

CPU Reproducer

import jax
import jax.numpy as jnp
import numpy as np
import scipy.special

jax.config.update("jax_enable_x64", True)

x = np.random.uniform(0, 1, 500_000)
%timeit -r 3 -n 1 scipy.special.betainc(4.5, 0.5, x)
# 110 ms ± 613 μs per loop (mean ± std. dev. of 3 runs, 1 loop each)

betainc = jax.jit(jax.scipy.special.betainc)

jax.config.update("jax_default_device", jax.devices("cpu")[0])
jx = jnp.asarray(x)
%timeit -r 1 -n 1 betainc(4.5, 0.5, jx).block_until_ready()  # JIT warmup
# 1.73 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r 3 -n 1 betainc(4.5, 0.5, jx).block_until_ready()
# 1.37 s ± 23.4 ms per loop (mean ± std. dev. of 3 runs, 1 loop each)

GPU reproducer

jax.config.update("jax_default_device", jax.devices("gpu")[0])
betainc = jax.jit(jax.scipy.special.betainc)
betainc.clear_cache()

for n in range(16, 26):
    print(2**n)
    x = np.random.uniform(0, 1, 2**n)
    %timeit -r 1 -n 1 scipy.special.betainc(4.5, 0.5, x)
    jx = jnp.asarray(x).block_until_ready()
    %timeit -r 1 -n 1 betainc(4.5, 0.5, jx).block_until_ready()  # cold JIT
    %timeit -r 1 -n 1 betainc(4.5, 0.5, jx).block_until_ready()  # warm JIT
    print()

Output:

Image

System info (python version, jaxlib version, accelerator, etc.)

jax:    0.5.2
jaxlib: 0.5.2
numpy:  2.2.5
python: 3.12.10 | packaged by conda-forge | (main, Apr 10 2025, 22:21:13) [GCC 13.3.0]
device info: NVIDIA GeForce RTX 3080-1, 1 local devices"
process_count: 1
platform: uname_result(system='Linux', node='melody', release='6.8.0-59-generic', version='#61-Ubuntu SMP PREEMPT_DYNAMIC Fri Apr 11 23:16:11 UTC 2025', machine='x86_64')


$ nvidia-smi
Tue May  6 15:34:17 2025       
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 550.144.03             Driver Version: 550.144.03     CUDA Version: 12.4     |
|-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  NVIDIA GeForce RTX 3080        Off |   00000000:09:00.0  On |                  N/A |
| 36%   52C    P2            133W /  340W |    2030MiB /  10240MiB |     40%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+
                                                                                         
+-----------------------------------------------------------------------------------------+
| Processes:                                                                              |
|  GPU   GI   CI        PID   Type   Process name                              GPU Memory |
|        ID   ID                                                               Usage      |
|=========================================================================================|
|    0   N/A  N/A      3551      G   /usr/lib/xorg/Xorg                            795MiB |
|    0   N/A  N/A      3839      G   /usr/bin/gnome-shell                          114MiB |
|    0   N/A  N/A      4452      G   /usr/libexec/xdg-desktop-portal-gnome         245MiB |
|    0   N/A  N/A      4924      G   ...brave/507/opt/brave.com/brave/brave          3MiB |
|    0   N/A  N/A      5087      G   ...e5f6352d94ab008661c97049791a7b04f09        365MiB |
|    0   N/A  N/A      5318      G   ...erProcess --variations-seed-version        139MiB |
|    0   N/A  N/A     10661      G   /usr/bin/gnome-system-monitor                  20MiB |
|    0   N/A  N/A     47448      G   /snap/slack/196/usr/lib/slack/slack            97MiB |
|    0   N/A  N/A    242100      C   ...iforge3/envs/pyscenarios/bin/python        220MiB |
+-----------------------------------------------------------------------------------------+
$ cat /proc/cpuinfo
processor	: 31
vendor_id	: AuthenticAMD
cpu family	: 23
model		: 113
model name	: AMD Ryzen 9 3950X 16-Core Processor
stepping	: 0
microcode	: 0x8701021
cpu MHz		: 2200.000
cache size	: 512 KB
physical id	: 0
siblings	: 32
core id		: 15
cpu cores	: 16
apicid		: 31
initial apicid	: 31
fpu		: yes
fpu_exception	: yes
cpuid level	: 16
wp		: yes
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 nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy 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 ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd 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
bugs		: sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass retbleed smt_rsb srso ibpb_no_ret
bogomips	: 6986.70
TLB size	: 3072 4K pages
clflush size	: 64
cache_alignment	: 64
address sizes	: 43 bits physical, 48 bits virtual
power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14]

crusaderky avatar May 06 '25 14:05 crusaderky

The implementation of betainc is here: https://github.com/jax-ml/jax/blob/579a1573cc82265c2b3245f2ee9ffd33f55fcd63/jax/_src/lax/special.py#L210-L297

Note that it's not a native operation, rather it's defined in terms of lax control flow operators.

jakevdp avatar May 06 '25 17:05 jakevdp

An easier to reproduce comparison (jax 0.6.1)

import jax
import jax.numpy as jnp
import numpy as np
import pandas as pd
import scipy.special

jax.config.update("jax_enable_x64", True)
betainc = jax.jit(jax.scipy.special.betainc)
betainc.clear_cache()

a = 4.5
b = 0.5

columns = [
    "samples",
    "scipy", 
    "jax cpu (cold jit)",
    "jax cpu (warm jit)",
    "jax gpu (cold jit)",
    "jax gpu (warm jit)",
]
rows = []
for n in range(0, 8):
    x = np.random.uniform(0, 1, 10**n)
    jx_cpu = jnp.asarray(x, device=jax.devices("cpu")[0]).block_until_ready()
    jx_gpu = jnp.asarray(x, device=jax.devices("gpu")[0]).block_until_ready()
    t1 = %timeit -o -q -r 1 -n 1 scipy.special.betainc(a, b, x)
    t2 = %timeit -o -q -r 1 -n 1 betainc(a, b, jx_cpu).block_until_ready()  # cold JIT
    t3 = %timeit -o -q -r 1 -n 1 betainc(a, b, jx_cpu).block_until_ready()  # warm JIT
    t4 = %timeit -o -q -r 1 -n 1 betainc(a, b, jx_gpu).block_until_ready()  # cold JIT
    t5 = %timeit -o -q -r 1 -n 1 betainc(a, b, jx_gpu).block_until_ready()  # warm JIT
    rows.append([10**n, t1.average, t2.average, t3.average, t4.average, t5.average])

df = pd.DataFrame(rows, columns=columns).set_index("samples")
(df * 1000).plot(logx=True, logy=True, grid=True, ylabel="ms")

Image

crusaderky avatar May 23 '25 09:05 crusaderky

FYI, betainc can be expressed as a function of hyp2f1 (new in JAX 0.6.1):

@jax.jit
def betainc2(a, b, x):
    return x**a * jax.scipy.special.hyp2f1(a, 1 - b, a + 1, x) / a / jax.scipy.special.beta(a, b)

However, the above is 20x slower than native betainc and has precision problems for x approaching to 1.

crusaderky avatar May 23 '25 09:05 crusaderky

The cause is structural: betainc lowers to a while_loop running Lentz's continued fraction, so the whole array re-executes until the worst element converges, and the loop is a fusion barrier. stdtr/stdtrit then inherit it.

I built a 3rd party library to deal with this and similar issues: chebax (https://github.com/andreshernandez-spec/chebax). It takes another route for the same functions: fixed-degree branchless polynomial kernels (betainc from baked Chebyshev tables, stdtrit as a fixed-count Newton), same work for every element, no loops, no fusion barrier, and the parameter gradients come from the same representation instead of extra looped series. Accuracy against 40-dps mpmath: betainc 7.5e-15, a,b gradients 2.0e-14, stdtr/stdtrit roundtrip ~5e-16.

The caveat is that the range of the beta parameters need to be determined ahead of time, the default in the library uses parameters in [0.1, 10]^2 (t dof in [0.2, 20]) and are uniform per call rather than per-element. So you don't get to have an array of a and b and x, but rather a and b are scalars

Measured head to head (RTX 3080 Laptop, jax 0.11, N = 2^24, medians of 25 interleaved reps, device-resident arrays; the script is experiments/06_betainc_stdtr_race.py in the repo if you want to rerun it on your 3080):

  • betainc f64: 79-133x over jax.scipy.special.betainc, depending on (a, b); f32: 13-16x
  • your CPU scenario (500k elements, host backend): 202x
  • stdtr f64: 59-60x against the betainc-composed form
  • max |chebax - jax| over the 16.7M points: 1.3e-14 to 3.7e-14
  • the ratio is flat in N from 2^20 up (~112x at the base case), which is what you would expect from a while_loop that charges every lane the worst element's trip count

One aside the agreement column surfaced: composing stdtr through betainc loses digits near x -> 1 (small |t|; the two sides differ by ~1e-9 there, and chebax's stdtr is tested against mpmath to 5e-14). scipy ships stdtr as a dedicated routine for the same reason.

andreshernandez-spec avatar Jul 31 '26 14:07 andreshernandez-spec