Repository navigation
Expand file tree
/
Copy pathdevice.py
More file actions
70 lines (58 loc) · 2.23 KB
/
Copy pathdevice.py
File metadata and controls
70 lines (58 loc) · 2.23 KB
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
64
65
66
67
68
69
70
import os
class Device:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Device, cls).__new__(cls)
cls._instance._initialize()
return cls._instance
def _initialize(self):
import sys
import os
# Ensure paradma is in path
paradma_path = os.path.join(os.getcwd(), "paradma")
if paradma_path not in sys.path:
sys.path.append(paradma_path)
self._current_device = 'cpu'
try:
self._cpu_backend = __import__('numpy')
# Paradma uses numpy as its base execution engine
pass
except ImportError:
self._cpu_backend = __import__('numpy')
print("Paradma not found. Falling back to Numpy.")
self._gpu_backend = None
# Check for CuPy availability
try:
import cupy
self._gpu_backend = cupy
print("CuPy found. GPU acceleration available.")
except ImportError:
print("CuPy not found. Running on CPU only.")
@property
def backend(self):
if self._current_device == 'gpu' and self._gpu_backend:
return self._gpu_backend
return self._cpu_backend
@property
def current_device(self):
return self._current_device
def set_device(self, device_type):
if device_type not in ['cpu', 'gpu']:
raise ValueError("Device type must be 'cpu' or 'gpu'.")
if device_type == 'gpu' and not self._gpu_backend:
raise RuntimeError("CuPy not available. Cannot set device to GPU.")
self._current_device = device_type
print(f"Device set to {self._current_device.upper()}")
def to_cpu(self, array):
if self._gpu_backend and isinstance(array, self._gpu_backend.ndarray):
return self._gpu_backend.asnumpy(array)
return array
def to_gpu(self, array):
if self._gpu_backend:
if isinstance(array, self._cpu_backend.ndarray):
return self._gpu_backend.asarray(array)
return array
raise RuntimeError("CuPy not available. Cannot move array to GPU.")
# Global device instance
device = Device()