-
Notifications
You must be signed in to change notification settings - Fork 440
/
Copy pathonnx_runtime.go
42 lines (36 loc) · 1.26 KB
/
onnx_runtime.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
//go:build cgo && onnxruntime
package onnx
// #cgo LDFLAGS: -lonnxruntime
// #include "onnx_runtime.h"
import "C"
import (
"fmt"
)
// NewOnnx returns an onnx that can perform inferences using an ONNX Runtime
// (https://onnxruntime.ai/) and the given model.
// It wraps the C calls to the ONNX Runtime API https://onnxruntime.ai/docs/api/c.
func NewOnnx(modelPath string, sizeTarget int) (Onnx, error) {
ort := &onnxRuntime{
api: C.GetApiBase(),
sizeTarget: sizeTarget,
}
if err := C.CreateSession(ort.api, C.CString(modelPath), &ort.session, &ort.memory); err != nil {
return nil, fmt.Errorf("create session: %v", C.GoString(C.GetErrorMessage(err)))
}
return ort, nil
}
// onnxRuntime implements the Onnx interface relying on a cgo call
// to a C ONNX Runtime library.
type onnxRuntime struct {
api *C.OrtApi
session *C.OrtSession
memory *C.OrtMemoryInfo
sizeTarget int
}
func (ort *onnxRuntime) Run(features []int32) ([]float32, error) {
target := make([]float32, ort.sizeTarget)
if err := C.Run(ort.api, ort.session, ort.memory, (*C.int32_t)(&features[0]), C.int64_t(len(features)), (*C.float)(&target[0]), C.int64_t(len(target))); err != nil {
return nil, fmt.Errorf("run: %v", C.GoString(C.GetErrorMessage(err)))
}
return target, nil
}