Skip to content

Instantly share code, notes, and snippets.

@nup002
Last active February 9, 2024 07:59
Show Gist options
  • Save nup002/0b396d5a37b6cb2aa71865aa993694e9 to your computer and use it in GitHub Desktop.
Save nup002/0b396d5a37b6cb2aa71865aa993694e9 to your computer and use it in GitHub Desktop.
A code snippet to import optional cupy
"""
This Gist illustrates how you can import cupy when it may or not be installed. Also works with frozen applications.
If cupy is not installed, or the CUDA_PATH system variable is not set, or the incorrect CUDA version is installed
(relevant for frozen applications), is_cupy_available = False.
"""
import warnings
is_cupy_available = False
try:
# Try to import cupy
with warnings.catch_warnings():
warnings.simplefilter("error") # Raise warnings as UserWarning exception
import cupy as cp # type:ignore[import-untyped]
import cupyx.scipy.fft as cpfft # type:ignore[import-untyped]
except (ModuleNotFoundError, UserWarning):
warnings.warn("CuPy is not installed, or you have not set the CUDA_PATH system variable.", stacklevel=2)
else:
# Test cupy
try:
cp.fft.fft(cp.random.rand(128))
except Exception as exc:
warnings.warn("CuPy threw an exception during testing. Have you installed CUDA 12.3? "
f"Exception message:: {exc}", stacklevel=2)
else:
print("CuPy imported and tested OK.")
is_cupy_available = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment