-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathcuda.py
63 lines (50 loc) · 1.39 KB
/
cuda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import numpy as np
gpu_enable = True
try:
import cupy as cp
cupy = cp
except ImportError:
gpu_enable = False
from dezero import Variable
def get_array_module(x):
"""Returns the array module for `x`.
Args:
x (dezero.Variable or numpy.ndarray or cupy.ndarray): Values to
determine whether NumPy or CuPy should be used.
Returns:
module: `cupy` or `numpy` is returned based on the argument.
"""
if isinstance(x, Variable):
x = x.data
if not gpu_enable:
return np
xp = cp.get_array_module(x)
return xp
def as_numpy(x):
"""Convert to `numpy.ndarray`.
Args:
x (`numpy.ndarray` or `cupy.ndarray`): Arbitrary object that can be
converted to `numpy.ndarray`.
Returns:
`numpy.ndarray`: Converted array.
"""
if isinstance(x, Variable):
x = x.data
if np.isscalar(x):
return np.array(x)
elif isinstance(x, np.ndarray):
return x
return cp.asnumpy(x)
def as_cupy(x):
"""Convert to `cupy.ndarray`.
Args:
x (`numpy.ndarray` or `cupy.ndarray`): Arbitrary object that can be
converted to `cupy.ndarray`.
Returns:
`cupy.ndarray`: Converted array.
"""
if isinstance(x, Variable):
x = x.data
if not gpu_enable:
raise Exception('CuPy cannot be loaded. Install CuPy!')
return cp.asarray(x)