To execute an ONNX model, follow these steps:
- Initialize the environment: Call
ort.InitializeEnvironment() and ensure you defer ort.DestroyEnvironment(). - Prepare Tensors: Create input and output tensors. For performance, it is recommended to create these before creating the session. Use
ort.NewTensor for existing data or ort.NewEmptyTensor[T] for pre-allocating output buffers. Always defer tensor.Destroy(). - Create a Session: Use
ort.NewAdvancedSession to link the model file, input/output names, and the pre-allocated tensors. - Run Inference: Call
session.Run(). This reads from the input tensors and writes results into the output tensors. - Access Data: Use
tensor.GetData() to retrieve a slice view of the results.
Note: For use cases where input/output shapes change, use the DynamicAdvancedSession type instead.
import (
"fmt"
ort "github.com/yalue/onnxruntime_go"
"os"
)
func main() {
// 1. Set library path and initialize
ort.SetSharedLibraryPath("path/to/onnxruntime.so")
err := ort.InitializeEnvironment()
if err != nil {
panic(err)
}
defer ort.DestroyEnvironment()
// 2. Prepare input and output tensors
inputData := []float32{0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9}
inputShape := ort.NewShape(2, 5)
inputTensor, err := ort.NewTensor(inputShape, inputData)
if err != nil { panic(err) }
defer inputTensor.Destroy()
outputShape := ort.NewShape(2, 3, 4)
outputTensor, err := ort.NewEmptyTensor[float32](outputShape)
if err != nil { panic(err) }
defer outputTensor.Destroy()
// 3. Create session
session, err := ort.NewAdvancedSession("path/to/network.onnx",
[]string{"Input 1 Name"}, []string{"Output 1 Name"},
[]ort.Value{inputTensor}, []ort.Value{outputTensor}, nil)
if err != nil { panic(err) }
defer session.Destroy()
// 4. Run inference
err = session.Run()
if err != nil { panic(err) }
// 5. Get results
outputData := outputTensor.GetData()
fmt.Println(outputData)
}