Skip to content

Commit c3c0b2c

Browse files
committed
Make BLAS flags check lazy and more actionable
It replaces the old warning that does not actually apply by a more informative and actionable one. This warning was for Ops that might use the alternative blas_headers, which rely on the Numpy C-API. However, regular PyTensor user has not used this for a while. The only Op that would use C-code with this alternative headers is the GEMM Op which is not included in current rewrites. Instead Dot22 or Dot22Scalar are introduced, which refuse to generate C-code altogether if the blas flags are missing.
1 parent a0fe30d commit c3c0b2c

File tree

3 files changed

+98
-33
lines changed

3 files changed

+98
-33
lines changed

doc/troubleshooting.rst

Lines changed: 64 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -145,44 +145,63 @@ How do I configure/test my BLAS library
145145
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
146146

147147
There are many ways to configure BLAS for PyTensor. This is done with the PyTensor
148-
flags ``blas__ldflags`` (:ref:`libdoc_config`). The default is to use the BLAS
149-
installation information in NumPy, accessible via
150-
``numpy.__config__.show()``. You can tell pytensor to use a different
151-
version of BLAS, in case you did not compile NumPy with a fast BLAS or if NumPy
152-
was compiled with a static library of BLAS (the latter is not supported in
153-
PyTensor).
148+
flags ``blas__ldflags`` (:ref:`libdoc_config`). If not specified, PyTensor will
149+
attempt to find a local BLAS library to link against, prioritizing specialized implementations.
150+
The details can be found in :func:`pytensor.link.c.cmodule.default_blas_ldflags`.
154151

155-
The short way to configure the PyTensor flags ``blas__ldflags`` is by setting the
156-
environment variable :envvar:`PYTENSOR_FLAGS` to ``blas__ldflags=XXX`` (in bash
157-
``export PYTENSOR_FLAGS=blas__ldflags=XXX``)
152+
Users can manually set the PyTensor flags ``blas__ldflags`` to link against a
153+
specific version. This is useful even if the default version is the desired one,
154+
as it will avoid the costly work of trying to find the best BLAS library at runtime.
158155

159-
The ``${HOME}/.pytensorrc`` file is the simplest way to set a relatively
160-
permanent option like this one. Add a ``[blas]`` section with an ``ldflags``
161-
entry like this:
156+
The PyTensor flags can be set in a few ways:
157+
1. In the ``${HOME}/.pytensorrc`` file.
162158

163159
.. code-block:: cfg
164160
165161
# other stuff can go here
166162
[blas]
167-
ldflags = -lf77blas -latlas -lgfortran #put your flags here
163+
ldflags = -llapack -lblas -lcblas # put your flags here
168164
169165
# other stuff can go here
170166
171-
For more information on the formatting of ``~/.pytensorrc`` and the
172-
configuration options that you can put there, see :ref:`libdoc_config`.
167+
2. In BASH before running your script:
168+
169+
.. code-block:: bash
170+
171+
export PYTENSOR_FLAGS="blas__ldflags='-llapack -lblas -lcblas'"
172+
173+
3. In an Ipython/Jupyter notebook before importing PyTensor:
174+
175+
.. code-block:: python
176+
177+
%set_env PYTENSOR_FLAGS=blas__ldflags='-llapack -lblas -lcblas'
178+
179+
180+
4. In `pytensor.config` directly:
181+
182+
.. code-block:: python
183+
184+
import pytensor
185+
pytensor.config.blas__ldflags = '-llapack -lblas -lcblas'
186+
187+
188+
(For more information on the formatting of ``~/.pytensorrc`` and the
189+
configuration options that you can put there, see :ref:`libdoc_config`.)
190+
191+
You can find the default BLAS library that PyTensor is linking against by
192+
checking ``pytensor.config.blas__ldflags``
193+
or running :func:`pytensor.link.c.cmodule.default_blas_ldflags`.
173194

174195
Here are some different way to configure BLAS:
175196

176-
0) Do nothing and use the default config, which is to link against the same
177-
BLAS against which NumPy was built. This does not work in the case NumPy was
178-
compiled with a static library (e.g. ATLAS is compiled by default only as a
179-
static library).
197+
0) Do nothing and use the default config.
198+
This will usually work great for conda/mamba/pixi installations of PyTensor.
199+
It will usually fail for pip installations of PyTensor.
180200

181201
1) Disable the usage of BLAS and fall back on NumPy for dot products. To do
182-
this, set the value of ``blas__ldflags`` as the empty string (ex: ``export
183-
PYTENSOR_FLAGS=blas__ldflags=``). Depending on the kind of matrix operations your
184-
PyTensor code performs, this might slow some things down (vs. linking with BLAS
185-
directly).
202+
this, set the value of ``blas__ldflags`` as the empty string.
203+
Depending on the kind of matrix operations your PyTensor code performs,
204+
this might slow some things down (vs. linking with BLAS directly).
186205

187206
2) You can install the default (reference) version of BLAS if the NumPy version
188207
(against which PyTensor links) does not work. If you have root or sudo access in
@@ -208,10 +227,29 @@ correctly (for example, for MKL this might be ``-lmkl -lguide -lpthread`` or
208227
``-lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -lguide -liomp5 -lmkl_mc
209228
-lpthread``).
210229

230+
5) Use an experimental such as Numba or JAX that perform their own BLAS optimizations,
231+
by setting the configuration mode to ``"NUMBA"`` or ``"JAX"`` and making sure those packages are installed.
232+
This configuration mode can be set in all the ways that the BLAS flags can be set, described above.
233+
234+
Alternatively, you can pass `mode='NUMBA'` when compiling individual PyTensor functions without changing the default.
235+
or use the ``config.change_flags`` context manager.
236+
237+
.. code-block:: python
238+
239+
from pytensor import function, config
240+
from pytensor.tensor import matrix
241+
242+
x = matrix('x')
243+
y = x @ x.T
244+
f = function([x], y, mode='NUMBA')
245+
246+
with config.change_flags(mode='NUMBA'):
247+
# compiling function that benefits from BLAS using NUMBA
248+
f = function([x], y)
249+
211250
.. note::
212251

213-
Make sure your BLAS
214-
libraries are available as dynamically-loadable libraries.
252+
Make sure your BLAS libraries are available as dynamically-loadable libraries.
215253
ATLAS is often installed only as a static library. PyTensor is not able to
216254
use this static library. Your ATLAS installation might need to be modified
217255
to provide dynamically loadable libraries. (On Linux this
@@ -267,7 +305,7 @@ configuration information. Then, it will print the running time of the same
267305
benchmarks for your installation. Try to find a CPU similar to yours in
268306
the table, and check that the single-threaded timings are roughly the same.
269307

270-
PyTensor should link to a parallel version of Blas and use all cores
308+
PyTensor should link to a parallel version of BLAS and use all cores
271309
when possible. By default it should use all cores. Set the environment
272310
variable "OMP_NUM_THREADS=N" to specify to use N threads.
273311

pytensor/link/c/cmodule.py

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2743,12 +2743,30 @@ def check_mkl_openmp():
27432743
)
27442744

27452745

2746-
def default_blas_ldflags():
2747-
"""Read local NumPy and MKL build settings and construct `ld` flags from them.
2746+
def default_blas_ldflags() -> str:
2747+
"""Look for an available BLAS implementation in the system.
2748+
2749+
This function tries to compile a simple C code that uses the BLAS
2750+
if the required files are found in the system.
2751+
It sequentially tries to link to the following implementations, until one is found:
2752+
1. Intel MKL with Intel OpenMP threading
2753+
2. Intel MKL with GNU OpenMP threading
2754+
3. Lapack + BLAS
2755+
4. BLAS alone
2756+
5. OpenBLAS
27482757
27492758
Returns
27502759
-------
2751-
str
2760+
blas flags: str
2761+
Blas flags needed to link to the BLAS implementation found in the system.
2762+
If no BLAS implementation is found, an empty string is returned.
2763+
2764+
Notes
2765+
-----
2766+
This function is triggered when `pytensor.config.blas__ldflags` is not given a user
2767+
default, and it is first accessed at runtime. It can be rather slow, so it is advised
2768+
to cache the results of this function in PYTENSORRC configuration file or
2769+
PyTensor environment flags.
27522770
27532771
"""
27542772

@@ -2947,6 +2965,14 @@ def check_libs(
29472965
except Exception as e:
29482966
_logger.debug(e)
29492967
_logger.debug("Failed to identify blas ldflags. Will leave them empty.")
2968+
warnings.warn(
2969+
"PyTensor could not link to a BLAS installation. Operations that might benefit from BLAS will be severely degraded.\n"
2970+
"This usually happens when PyTensor is installed via pip. We recommend it be installed via conda/mamba/pixi instead.\n"
2971+
"Alternatively, you can use an experimental backend such as Numba or JAX that perform their own BLAS optimizations, "
2972+
"by setting `pytensor.config.mode == 'NUMBA'` or passing `mode='NUMBA'` when compiling a PyTensor function.\n"
2973+
"For more options and details see https://pytensor.readthedocs.io/en/latest/troubleshooting.html#how-do-i-configure-test-my-blas-library",
2974+
UserWarning,
2975+
)
29502976
return ""
29512977

29522978

pytensor/tensor/blas_headers.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,11 @@ def blas_header_text():
742742

743743
blas_code = ""
744744
if not config.blas__ldflags:
745+
# This code can only be reached by compiling a function with a manually specified GEMM Op.
746+
# Normal PyTensor usage will end up with Dot22 or Dot22Scalar instead,
747+
# which opt out of C-code completely if the blas flags are missing
748+
_logger.warning("Using NumPy C-API based implementation for BLAS functions.")
749+
745750
# Include the Numpy version implementation of [sd]gemm_.
746751
current_filedir = Path(__file__).parent
747752
blas_common_filepath = current_filedir / "c_code/alt_blas_common.h"
@@ -1003,10 +1008,6 @@ def blas_header_text():
10031008
return header + blas_code
10041009

10051010

1006-
if not config.blas__ldflags:
1007-
_logger.warning("Using NumPy C-API based implementation for BLAS functions.")
1008-
1009-
10101011
def mkl_threads_text():
10111012
"""C header for MKL threads interface"""
10121013
header = """

0 commit comments

Comments
 (0)