Skip to content

Backend & Hardware Acceleration

MPNeuralNetwork supports both CPU and GPU execution through a unified backend interface. This module handles the abstraction between numpy (CPU) and cupy (GPU).

Configuration

The backend is selected at runtime via the MPNN_BACKEND environment variable.

  • CPU (Default): MPNN_BACKEND=numpy
  • GPU (NVIDIA): MPNN_BACKEND=cupy (Requires cupy to be installed)

API Reference

Global Types

mpneuralnetwork.backend.DTYPE = cp.float32 module-attribute

mpneuralnetwork.backend.ArrayType = np.ndarray | Any module-attribute

TypeAlias: Union[np.ndarray, cp.ndarray] - Represents an array on either CPU or GPU.

Functions

mpneuralnetwork.backend.to_device(array)

Transfers an array to the current backend device.

If the backend is CPU (NumPy), returns the array as a numpy array. If the backend is GPU (CuPy), moves the array to GPU memory.

Parameters:

Name Type Description Default
array ArrayType

The input array (numpy or cupy).

required

Returns:

Name Type Description
ArrayType ArrayType

The array on the configured device.

Source code in src/mpneuralnetwork/backend.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def to_device(array: ArrayType) -> ArrayType:
    """Transfers an array to the current backend device.

    If the backend is CPU (NumPy), returns the array as a numpy array.
    If the backend is GPU (CuPy), moves the array to GPU memory.

    Args:
        array (ArrayType): The input array (numpy or cupy).

    Returns:
        ArrayType: The array on the configured device.
    """
    if xp.__name__ == "cupy":
        return xp.asarray(array)
    return np.asarray(array)

mpneuralnetwork.backend.to_host(array)

Transfers an array to the CPU (Host).

If the array is on GPU (CuPy), it is transferred to CPU. If it's already on CPU, it is returned as is.

Parameters:

Name Type Description Default
array ArrayType

The input array.

required

Returns:

Name Type Description
NDArray NDArray

A NumPy array.

Source code in src/mpneuralnetwork/backend.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def to_host(array: ArrayType) -> NDArray:
    """Transfers an array to the CPU (Host).

    If the array is on GPU (CuPy), it is transferred to CPU.
    If it's already on CPU, it is returned as is.

    Args:
        array (ArrayType): The input array.

    Returns:
        NDArray: A NumPy array.
    """
    if hasattr(array, "get"):
        return array.get()  # type: ignore
    return np.asarray(array)

mpneuralnetwork.backend.get_backend()

Returns the current backend module.

Returns:

Name Type Description
ModuleType ModuleType

numpy or cupy module.

Source code in src/mpneuralnetwork/backend.py
68
69
70
71
72
73
74
def get_backend() -> ModuleType:
    """Returns the current backend module.

    Returns:
        ModuleType: `numpy` or `cupy` module.
    """
    return xp