-
Notifications
You must be signed in to change notification settings - Fork 3
/
jit.go
252 lines (203 loc) · 6.17 KB
/
jit.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// +build pytorch_jit
package pytorch
// #include "cbits/predictor.hpp"
// #include <stdlib.h>
// #include <stdint.h>
//
// size_t size_of_ivalue_tuple = sizeof(Torch_IValueTuple);
// size_t size_of_ivalue = sizeof(Torch_IValue);
//
import "C"
import (
"fmt"
"runtime"
"unsafe"
)
// JITModule is a jit compiled PyTorch module
type JITModule struct {
context C.Torch_JITModuleContext
}
// CompileTorchScript compiles TorchScript and returns a *JITModule
func CompileTorchScript(torchScript string) (*JITModule, error) {
cstr := C.CString(torchScript)
defer C.free(unsafe.Pointer(cstr))
var cErr C.Torch_Error
ctx := C.Torch_CompileTorchScript(cstr, &cErr)
if err := checkError(cErr); err != nil {
return nil, err
}
mod := &JITModule{context: ctx}
runtime.SetFinalizer(mod, (*JITModule).finalize)
return mod, nil
}
// LoadJITModule loads module from file
func LoadJITModule(path string) (*JITModule, error) {
cstr := C.CString(path)
defer C.free(unsafe.Pointer(cstr))
var cErr C.Torch_Error
ctx := C.Torch_LoadJITModule(cstr, &cErr)
if err := checkError(cErr); err != nil {
return nil, err
}
mod := &JITModule{context: ctx}
runtime.SetFinalizer(mod, (*JITModule).finalize)
// TODO handle errors
return mod, nil
}
// Save saves Module to given path
func (m *JITModule) Save(path string) error {
cstr := C.CString(path)
defer C.free(unsafe.Pointer(cstr))
var cErr C.Torch_Error
C.Torch_ExportJITModule(m.context, cstr, &cErr)
if err := checkError(cErr); err != nil {
return err
}
// TODO handle errors
return nil
}
// GetMethod returns a method from a JITModule
func (m *JITModule) GetMethod(method string) (*JITModuleMethod, error) {
cstr := C.CString(method)
defer C.free(unsafe.Pointer(cstr))
var cErr C.Torch_Error
context := C.Torch_JITModuleGetMethod(m.context, cstr, &cErr)
if err := checkError(cErr); err != nil {
return nil, err
}
met := &JITModuleMethod{context: context, Module: m, Name: method}
runtime.SetFinalizer(met, (*JITModuleMethod).finalize)
return met, nil
}
// RunMethod executes given method with tensors or tuples as input
func (m *JITModule) RunMethod(method string, inputs ...interface{}) (interface{}, error) {
met, err := m.GetMethod(method)
if err != nil {
return nil, err
}
return met.Run(inputs...)
}
// Forward exectures forward method of the module (forward propagation)
func (m *JITModule) Forward(inputs ...interface{}) (interface{}, error) {
return m.RunMethod("forward", inputs...)
}
// GetMethodNames returns all method names from the module
func (m *JITModule) GetMethodNames() []string {
var resLen C.ulong
cnamesPtr := C.Torch_JITModuleGetMethodNames(m.context, &resLen)
resSlice := (*[1 << 30]*C.char)(unsafe.Pointer(cnamesPtr))[:resLen:resLen]
defer C.free(unsafe.Pointer(cnamesPtr))
names := make([]string, len(resSlice))
for i, name := range resSlice {
names[i] = C.GoString(name)
C.free(unsafe.Pointer(name))
}
return names
}
func (m *JITModule) finalize() {
C.Torch_DeleteJITModule(m.context)
}
// JITModuleMethod is single method from a JITModule
type JITModuleMethod struct {
context C.Torch_JITModuleMethodContext
Module *JITModule
Name string
}
// Run executes given method with tensors as input
func (m *JITModuleMethod) Run(inputs ...interface{}) (interface{}, error) {
ivalues := make([]C.Torch_IValue, len(inputs))
for i, t := range inputs {
var err error
ivalues[i], err = convertGoValueToIValue(t)
if err != nil {
return nil, err
}
}
defer freeIValues(ivalues)
var iValuePtr *C.Torch_IValue
if len(ivalues) > 0 {
iValuePtr = (*C.Torch_IValue)(&ivalues[0])
}
var cErr C.Torch_Error
ival := C.Torch_JITModuleMethodRun(
m.context,
iValuePtr,
C.ulong(len(ivalues)),
&cErr,
)
if err := checkError(cErr); err != nil {
return nil, err
}
defer freeIValues([]C.Torch_IValue{ival})
runtime.KeepAlive(inputs)
return convertIValueToGoType(ival)
}
// Arguments returns method arguments for the method schema
func (m *JITModuleMethod) Arguments() []JITModuleMethodArgument {
var resSize C.ulong
resPtr := C.Torch_JITModuleMethodArguments(m.context, &resSize)
defer C.free(unsafe.Pointer(resPtr))
resSlice := (*[1 << 30]C.Torch_ModuleMethodArgument)(unsafe.Pointer(resPtr))[:resSize:resSize]
args := make([]JITModuleMethodArgument, int(resSize))
for i, arg := range resSlice {
args[i] = JITModuleMethodArgument{
Name: C.GoString(arg.name),
Type: C.GoString(arg.typ),
}
C.free(unsafe.Pointer(arg.typ))
C.free(unsafe.Pointer(arg.name))
}
return args
}
// Returns returns method return type information for the method schema
func (m *JITModuleMethod) Returns() []JITModuleMethodArgument {
var resSize C.ulong
resPtr := C.Torch_JITModuleMethodReturns(m.context, &resSize)
defer C.free(unsafe.Pointer(resPtr))
resSlice := (*[1 << 30]C.Torch_ModuleMethodArgument)(unsafe.Pointer(resPtr))[:resSize:resSize]
args := make([]JITModuleMethodArgument, int(resSize))
for i, arg := range resSlice {
args[i] = JITModuleMethodArgument{
Name: C.GoString(arg.name),
Type: C.GoString(arg.typ),
}
C.free(unsafe.Pointer(arg.typ))
C.free(unsafe.Pointer(arg.name))
}
return args
}
func (m *JITModuleMethod) finalize() {
C.Torch_DeleteJITModuleMethod(m.context)
}
// JITModuleMethodArgument contains information of a single method argument
type JITModuleMethodArgument struct {
Name string
Type string
}
func convertGoValueToIValue(val interface{}) (C.Torch_IValue, error) {
switch v := val.(type) {
case *Tensor:
return C.Torch_IValue{
itype: C.Torch_IValueTypeTensor,
data_ptr: unsafe.Pointer(v.context),
}, nil
case Tuple:
tuple := (*C.Torch_IValueTuple)(C.malloc((C.size_t)(C.size_of_ivalue_tuple)))
tuple.values = (*C.Torch_IValue)(C.malloc(C.size_of_ivalue * C.ulong(len(v))))
tuple.length = C.ulong(len(v))
valuesSlice := (*[1 << 30]C.Torch_IValue)(unsafe.Pointer(tuple.values))[:tuple.length:tuple.length]
for i, val := range v {
var err error
valuesSlice[i], err = convertGoValueToIValue(val)
if err != nil {
return C.Torch_IValue{}, err
}
}
return C.Torch_IValue{
itype: C.Torch_IValueTypeTuple,
data_ptr: unsafe.Pointer(tuple),
}, nil
default:
return C.Torch_IValue{}, fmt.Errorf("invalid input type for run %T", val)
}
}