-
Book Overview & Buying
-
Table Of Contents
GPU-Accelerated Computing with Python 3 and CUDA
By :
Given CuPy's API similarity to NumPy, it's natural to consider writing hardware-agnostic code: code that runs on the GPU (using CuPy) when available, and otherwise falls back to the CPU (using NumPy).
To achieve this, CuPy should be treated as an optional dependency, ensuring users without a GPU are not forced to install it.
The following code snippet can be used to import CuPy when available, or else fall back to NumPy:
import numpy as np
try:
import cupy as xp
CUPY_IS_INSTALLED = True
except ImportError:
xp = np
CUPY_IS_INSTALLED = False
Based on the value of CUPY_IS_INSTALLED, different code paths can be followed. Additionally, xp can be used as the hardware-agnostic dispatcher that points to cupy when it is available and to numpy when it is not. xp should be used instead of cp throughout the code.
The dispatcher can be inferred at runtime from the array type by checking whether it is of the numpy.ndarray type, and otherwise...