-
Notifications
You must be signed in to change notification settings - Fork 46
/
device.go
126 lines (106 loc) · 2.45 KB
/
device.go
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package gotch
import (
"log"
lib "github.com/sugarme/gotch/libtch"
)
type Device struct {
Name string
Value int
}
type Cuda Device
var (
CPU Device = Device{Name: "CPU", Value: -1}
CUDA Cuda = Cuda{Name: "CUDA", Value: 0}
)
func CudaBuilder(v uint) Device {
// TODO: fully initiate cuda here
return Device{Name: "CUDA", Value: int(v)}
}
// NewCuda creates a cuda device (default) if available
// If will be panic if cuda is not available.
func NewCuda() Device {
var d Cuda
if !d.IsAvailable() {
log.Fatalf("Cuda is not available.")
}
return CudaBuilder(0)
}
// Cuda methods:
// =============
// DeviceCount returns the number of GPU that can be used.
func (cu Cuda) DeviceCount() int64 {
cInt := lib.AtcCudaDeviceCount()
return int64(cInt)
}
// CudnnIsAvailable returns true if cuda support is available
func (cu Cuda) IsAvailable() bool {
return lib.AtcCudaIsAvailable()
}
// CudnnIsAvailable return true if cudnn support is available
func (cu Cuda) CudnnIsAvailable() bool {
return lib.AtcCudnnIsAvailable()
}
// CudnnSetBenchmark sets cudnn benchmark mode
//
// When set cudnn will try to optimize the generators during the first network
// runs and then use the optimized architecture in the following runs. This can
// result in significant performance improvements.
func (cu Cuda) CudnnSetBenchmark(b bool) {
switch b {
case true:
lib.AtcSetBenchmarkCudnn(1)
case false:
lib.AtcSetBenchmarkCudnn(0)
}
}
// Device methods:
//================
func (d Device) CInt() CInt {
switch {
case d.Name == "CPU":
return -1
case d.Name == "CUDA":
// TODO: create a function to retrieve cuda_index
var deviceIndex int = d.Value
return CInt(deviceIndex)
default:
log.Fatal("Not reachable")
return 0
}
}
func (d Device) OfCInt(v CInt) Device {
switch {
case v == -1:
return Device{Name: "CPU", Value: 1}
case v >= 0:
return CudaBuilder(uint(v))
default:
log.Fatalf("Unexpected device %v", v)
}
return Device{}
}
// CudaIfAvailable returns a GPU device if available, else default to CPU
func (d Device) CudaIfAvailable() Device {
switch {
case CUDA.IsAvailable():
return CudaBuilder(0)
default:
return CPU
}
}
// IsCuda returns whether device is a Cuda device
func (d Device) IsCuda() bool {
if d.Name == "CPU" {
return false
}
return true
}
// CudaIfAvailable returns a GPU device if available, else CPU.
func CudaIfAvailable() Device {
switch {
case CUDA.IsAvailable():
return CudaBuilder(0)
default:
return CPU
}
}