BLAS threading and calling Einsums from your own threads#
Einsums does not implement its own linear algebra kernels. It calls BLAS and LAPACK, and the threading model of the library you link against constrains how you are allowed to call Einsums.
The short version: if every call into Einsums comes from one thread, or from threads Einsums itself created, anything works and you can stop reading. If you plan to call Einsums concurrently from threads you created, read on, because the default conda-forge OpenBLAS will silently give you wrong answers.
The two conda-forge OpenBLAS builds#
conda-forge ships OpenBLAS in two threading flavors, distinguished by the build string:
$ conda search -c conda-forge 'libopenblas=0.3.32'
libopenblas 0.3.32 openmp_he657e61_0 conda-forge
libopenblas 0.3.32 pthreads_hddb8425_0 conda-forge
The environment file generated by merge_yml.py resolves to the openmp_
build. To see which one you actually have:
import ctypes
handle = ctypes.CDLL(None)
handle.openblas_get_config.restype = ctypes.c_char_p
print(handle.openblas_get_config().decode())
# OpenBLAS 0.3.32 NO_AFFINITY USE_OPENMP VORTEX MAX_THREADS=128
The presence or absence of USE_OPENMP in that string is the thing to look
for. Note that USE_LOCKING never appears in it, in either build, so you
cannot use the config string to check for locking directly.
Why the OpenMP build breaks under caller-created threads#
An OpenMP-built OpenBLAS indexes its internal scratch buffers by
omp_get_thread_num(). That function returns 0 for any thread that is not
inside an OpenMP parallel region, which includes every thread you create
yourself: std::thread, a Python ThreadPoolExecutor, or anything else.
So several caller-created threads calling into BLAS at once all select buffer zero and write over each other. The failure mode is the bad one:
No crash, no error, no warning. Just wrong numbers.
Non-deterministic, so results differ from run to run.
Size-dependent. Small matrices do not reach the buffered path, so the same code can be exactly right on a small test case and wrong on a large one.
Invisible to ThreadSanitizer, because OpenBLAS is not instrumented. A clean TSan run does not clear a third-party library.
The pthreads_ build does not have this problem: it manages its own threads
and locks the buffer pool accordingly.
This is also why a C++ #pragma omp parallel for over independent BLAS calls
is safe with the OpenMP build while the equivalent std::thread loop is not.
The OpenMP threads form a real team, so omp_get_thread_num() returns
distinct values and each gets its own buffer.
What this affects in Einsums today#
Most of the public API is out of reach, which is why this has not surfaced before, but one Python path is not:
The Python bindings hold the GIL across the eager numeric entry points, so concurrent eager calls from Python threads serialize and never overlap inside BLAS.
Graph.execute,Graph.run_setup, andPipeline.executeare annotatedAPIARY_RELEASE_GIL. Python threads that execute graphs concurrently can therefore overlap inside BLAS, which is the caller-created-thread pattern above. On theopenmp_build, execute graphs from one Python thread at a time.OpenMPExecutoruses OpenMP parallel regions, which are safe.The
GEMMBatchingpass lowers toblas::gemm_batch, whose parallel loop is OpenMP, also safe.DataflowExecutorruns nodes on aTaskPoolofstd::threadworkers, which is the pattern at risk. A stress test of 48 independent 250x250 GEMMs across three executors, repeated, produced exact results, so there is no known reproducer through this path. Treat it as untested rather than proven safe, and prefer the OpenMP executor for BLAS-heavy graphs if you are on theopenmp_build.
It becomes reachable more broadly the moment any of these happens:
a graph is executed from a Python thread pool (see above), or an
APIARY_RELEASE_GILannotation is added to an eager numeric binding and a caller drives it from one,C++ code calls Einsums from
std::threadworkers rather than an OpenMP region, orthe module starts declaring free-threaded support, see below.
All are reasonable things to want. Parallelizing over independent work items from Python, with serial BLAS underneath, is how psi4 structures its DLPNO pair loops, and it is a natural fit for Einsums too.
Free-threaded Python#
conda-forge ships free-threaded CPython builds (cp313t and later), where
there is no GIL to serialize anything. That removes the accident that currently
protects Einsums, so the two features are in direct conflict: free-threading
support and the OpenMP OpenBLAS cannot both be adopted.
Today Einsums is protected on those interpreters, but by accident rather than
design. Its pybind11 module does not declare Py_MOD_GIL_NOT_USED
(pybind11 spells this py::mod_gil_not_used()), so CPython re-enables the
GIL when it imports Einsums and says so:
RuntimeWarning: The global interpreter lock (GIL) has been enabled to load
module 'einsums._core', which has not declared that it can run safely
without the GIL. To override this behavior and keep the GIL disabled (at
your own risk), run with PYTHON_GIL=0 or -Xgil=0.
A free-threaded interpreter loading Einsums therefore stops being free-threaded. That is what makes the current state safe, and it is why nobody has hit this.
Setting PYTHON_GIL=0 overrides the fallback, which is exactly the state
adding the opt-in would produce permanently. Measured on a cp314t
interpreter with stock bindings, no APIARY_RELEASE_GIL anywhere, running 91
concurrent syev calls of order 161 from a ten-worker pool:
Configuration |
Max eigenvalue error |
|---|---|
GIL auto-re-enabled (the default today) |
5.1e-13 |
|
6.2e+05, and 2.6e+03 on a rerun |
|
5.1e-13 |
So free-threading requires the pthreads_ OpenBLAS (or MKL) as a hard
prerequisite, not as a tuning option. Adding py::mod_gil_not_used() while
still linked against the openmp_ build would turn a correct library into a
silently wrong one for any threaded caller.
Building against a free-threaded interpreter also needs a CMake hint, because
FindPython will otherwise reject the t ABI and quietly fall back to
another interpreter on the system:
cmake -S . -B build -DPython_ROOT_DIR="$CONDA_PREFIX" \
-DPython_EXECUTABLE="$CONDA_PREFIX/bin/python" \
-DPython_FIND_ABI="OFF;ANY;ANY;ON" -DPython_FIND_STRATEGY=LOCATION
The fourth Python_FIND_ABI field is the free-threaded flag, and needs CMake
3.30 or newer.
A CI leg covers this. merge_yml.py --free-threaded swaps the interpreter pin
for the t ABI, and the free-threaded job builds the tree against it, runs
the full suite, then re-runs the Python tests under PYTHON_GIL=0. The second
pass is the one that matters: without it CPython re-enables the GIL on import and
the leg would only prove the tree compiles. Reproduce it locally with
./devtools/docker/run-ci-leg.sh free-threaded.
That leg drives Einsums from a single Python thread, so it does not exercise the hazard described above, which needs concurrent callers. It guards the build and the GIL-free serial path, not thread safety.
Switching to the pthreads build#
conda install -c conda-forge 'libopenblas=*=pthreads*'
Two things change with it, and both matter:
You must set
OPENBLAS_NUM_THREADS=1. The pthreads build does not readOMP_NUM_THREADS, so the usual OpenMP knobs do not reach it, and every one of your worker threads will spawn a full OpenBLAS thread pool of its own. Measured on a DLPNO-MP2 pair loop, leaving it unpinned was 2.6x slower than serial (480 ms to 5097 ms at four workers).Pinning it also turns off OpenBLAS-internal threading for large single GEMMs. If your workload is one big contraction at a time rather than many independent small ones, that is a real loss. Measure both shapes before changing an environment wholesale.
With the pthreads build and OPENBLAS_NUM_THREADS=1, a pair-parallel
DLPNO-MP2 orbital transform gave bit-identical energies at 1, 2, 4 and 10
workers, and ran 1.74x faster than serial. The same code on the openmp_
build produced a different (wrong) answer on every run.
MKL is safe to call from caller-created threads and needs none of this, if it is an option for your platform. It has a different problem instead, described next.
MKL inside Einsums’ own OpenMP regions#
The OpenBLAS hazard above is about caller-created threads. MKL’s is the mirror image: it is fine on those, and unsafe inside a parallel region Einsums opened.
MKL carries its own OpenMP runtime, normally libiomp5, while Einsums is
built against the compiler’s, normally libgomp.
The two do not share ICVs, and MKL’s nested check asks its runtime whether a
region is active.
Inside a libgomp region that check answers no, so MKL does not take its
nested-serial path: every member of Einsums’ team forks a full MKL team of its
own.
The result is not merely oversubscribed.
The calls disagree about how wide they are, and the answers come back
nondeterministic: on a water dimer, one DLPNO-CCSD residual evaluated twice at
identical amplitudes differed in 18 of 82 doubles blocks by up to 2.8e-14, and
the solve that consumed those residuals diverged.
Pinning either side to one thread removed both effects and reproduced the
serial energy exactly.
Einsums handles this itself, and no environment variable is needed.
VendorWidthFence, on every BLAS wrapper that forwards to the vendor, clamps
a vendor that exposes a per-thread thread count to one thread whenever
omp_in_parallel() is true, and restores the caller’s count afterwards.
OpenBLAS needs nothing there because it reads Einsums’ own ICV and takes its
nested-serial path unaided.
Removing the clamp is what the DLPNO chunk-invariance and dimer LCCSD tests
detect, so it is a gate rather than a tuning knob.