Documentation
¶
Overview ¶
Package onnxbackend implements an ONNX Runtime (ORT) compute backend for GoMLX (github.com/gomlx/compute).
It allows GoMLX models to be executed via ONNX Runtime using either CPU or CUDA (NVIDIA GPU). It supports dynamic shapes and exporting trained models to standard .onnx model files.
Registration & Initialization ¶
Importing this package registers the backend under the names "onnxruntime" and "onnx" with the GoMLX compute registry:
import _ "github.com/gomlx/compute-onnx"
Once imported, the backend can be selected automatically by `compute.New()` using the GOMLX_BACKEND environment variable:
GOMLX_BACKEND=onnx go run github.com/gomlx/gomlx/examples/adult/demo
Or created programmatically using `compute.NewWithConfig("onnx")` or directly via New:
backend, err := onnxbackend.New("cuda,log=2")
Configuration Options ¶
Configuration options can be specified in the GOMLX_BACKEND environment variable as "onnx:<options>" (or "onnxruntime:<options>") or passed directly to New:
Accelerator Selection:
- cpu: Force CPU execution. GOMLX_BACKEND=onnx:cpu
- cuda / gpu: Force CUDA GPU execution using ONNX Runtime CUDA Execution Provider via IoBinding. GOMLX_BACKEND=onnx:cuda
- <path/to/libonnxruntime.so>: Explicit path to the ONNX Runtime shared library file (bypasses ONNXRUNTIME_SHARED_LIBRARY_PATH). GOMLX_BACKEND=onnx:/path/to/libonnxruntime.so
- (empty / default): Automatically detects if an NVIDIA GPU is available and defaults to CUDA, falling back to CPU otherwise. GOMLX_BACKEND=onnx
ONNX Runtime Internal Logging:
- log=<level>: Sets ONNX Runtime internal logging severity level:
- log=0: Errors only (ERROR)
- log=1: Warnings (WARNING)
- log=2: Informational (INFO)
- log=3: Verbose (VERBOSE)
Example:
GOMLX_BACKEND="onnx:cuda,log=2"
ONNX Runtime Shared Libraries & Auto-Installation ¶
The backend automatically locates or manages the required ONNX Runtime shared library (libonnxruntime.so / onnxruntime.dll):
- Custom Library Path: Set the ONNXRUNTIME_SHARED_LIBRARY_PATH environment variable or pass an explicit library path in the configuration string (e.g. "onnx:/path/to/libonnxruntime.so") to point directly to the shared library binary. Specifying an explicit path in the configuration string bypasses ONNXRUNTIME_SHARED_LIBRARY_PATH.
- Auto-Installation: If no library path is provided, the backend automatically downloads and extracts prebuilt official ONNX Runtime binaries locally (e.g. ~/.local/lib/onnxruntime/ on Linux).
- Disabling Auto-Installation: Set the environment variable GOMLX_NO_AUTO_INSTALL=1 (or NoAutoInstallEnv), or call EnableAutoInstall(false) programmatically before initializing the backend to disable automatic downloads (useful for offline environments or container deployments).
Debugging & Saving Models on Failure ¶
If graph compilation or session creation fails, setting the environment variable GOMLX_ONNX_SAVE_ON_FAILURE (or SaveOnFailureEnv) to a file path instructs the ONNX backend to save the serialized ONNX model protobuf bytes to that file path for debugging and log a notification:
GOMLX_ONNX_SAVE_ON_FAILURE="/tmp/failed_model.onnx"
Inspecting & Pretty-Printing `.onnx` Files ¶
The CLI tool in `github.com/gomlx/compute-onnx/cmd/onnx_printer` pretty-prints the contents of `.onnx` model files in the terminal, displaying model metadata, input/output tensors with GoMLX shapes (shapes.Shape), initializers/constants, and graph operations on a single line per op:
go run github.com/gomlx/compute-onnx/cmd/onnx_printer path/to/model.onnx
Flags:
- max_items / n: Controls the maximum number of constant array elements printed (default 10).
- show_doc: Includes docstrings if present.
For interactive graphical visualization of ONNX models, `.onnx` files can also be opened using Netron (https://netron.app/).
Index ¶
- Constants
- func EnableAutoInstall(enable bool)
- func IsSupportedPlatform() bool
- func LoadModel(backend compute.Backend, r io.Reader) (compute.Executable, error)
- func MakeScalar(f *graph.Function, value any, dtype dtypes.DType) (compute.Value, error)
- func New(config string) (compute.Backend, error)
- func ParseGOMLXBackendEnv(envVal string) (string, error)
- func SaveModel(backend compute.Backend, executable compute.Executable, w io.Writer, ...) error
- type Backend
- func (b *Backend) BufferFromFlatData(deviceNum compute.DeviceNum, flat any, shape shapes.Shape) (compute.Buffer, error)
- func (b *Backend) Builder(name string) compute.Builder
- func (b *Backend) Capabilities() compute.Capabilities
- func (b *Backend) Config() string
- func (b *Backend) Description() string
- func (b *Backend) DeviceDescription(deviceNum compute.DeviceNum) string
- func (b *Backend) ExecutionProvider() string
- func (b *Backend) Finalize()
- func (b *Backend) HasSharedBuffers() bool
- func (b *Backend) IsFinalized() bool
- func (b *Backend) KeepModelProto() bool
- func (b *Backend) LogSeverity() int
- func (b *Backend) Name() string
- func (b *Backend) NewSharedBuffer(deviceNum compute.DeviceNum, shape shapes.Shape) (compute.Buffer, any, error)
- func (b *Backend) NumDevices() int
- func (b *Backend) SetKeepModelProto(keep bool)
- func (b *Backend) String() string
- func (b *Backend) Version() string
- func (b *Backend) WebVersion() string
- type Buffer
- type Builder
- type Executable
- type Function
- type Node
Constants ¶
const (
BackendName = "onnxruntime"
)
const NoAutoInstallEnv = "GOMLX_NO_AUTO_INSTALL"
NoAutoInstallEnv is the environment variable that, when set, disables automatic downloading and installation of prebuilt ONNX Runtime shared libraries.
const SaveOnFailureEnv = native.SaveOnFailureEnv
Variables ¶
This section is empty.
Functions ¶
func EnableAutoInstall ¶ added in v0.1.2
func EnableAutoInstall(enable bool)
EnableAutoInstall controls whether the backend automatically downloads and installs prebuilt ONNX Runtime shared libraries if none are found.
func IsSupportedPlatform ¶
func IsSupportedPlatform() bool
IsSupportedPlatform returns true if the host OS and CPU architecture are supported by ONNX Runtime binaries.
func LoadModel ¶
LoadModel loads an ONNX model from an io.Reader and compiles it into a runnable compute.Executable. It parses input and output tensor shapes and data types directly from the ONNX ModelProto and creates an ONNX Runtime session ready for execution.
func MakeScalar ¶ added in v0.1.1
MakeScalar constructs a 0D scalar constant tensor in the given function.
func ParseGOMLXBackendEnv ¶ added in v0.1.2
ParseGOMLXBackendEnv parses a GOMLX_BACKEND environment variable string (e.g. "onnx:cpu", "onnx", "onnxruntime:cuda,log=2"). It verifies that the backend selection is "onnx" or "onnxruntime", strips the backend name prefix, and returns the configuration options string.
func SaveModel ¶
func SaveModel(backend compute.Backend, executable compute.Executable, w io.Writer, inputNames []string, outputNames []string) error
SaveModel exports the computation graph associated with the given executable as an ONNX model file/stream. It verifies that both backend and executable belong to the ONNX backend package. If inputNames or outputNames are provided (non-empty), they rename the graph's inputs and outputs and update all corresponding internal node edge references before saving. If inputNames or outputNames are nil or empty, default or pre-existing graph names (e.g., "arg_0", "output_0") are retained.
Note: The backend must have had KeepModelProto set to true prior to compiling the executable, otherwise SaveModel will return an error indicating that the graph proto was discarded.
Types ¶
type Backend ¶
type Backend struct {
// contains filtered or unexported fields
}
Backend represents an ONNX Runtime backed compute.Backend.
func (*Backend) BufferFromFlatData ¶
func (*Backend) Capabilities ¶
func (b *Backend) Capabilities() compute.Capabilities
func (*Backend) Description ¶
func (*Backend) DeviceDescription ¶
func (*Backend) ExecutionProvider ¶ added in v0.1.4
ExecutionProvider returns the execution provider configured for the backend (e.g. "webgpu", "wasm", "cuda", or "").
func (*Backend) HasSharedBuffers ¶
func (*Backend) IsFinalized ¶
func (*Backend) KeepModelProto ¶
KeepModelProto returns whether compiled Executable instances retain their graph *onnx.ModelProto.
func (*Backend) LogSeverity ¶ added in v0.1.4
LogSeverity returns the configured log severity level (0=verbose, 1=info, 2=warning, 3=error, 4=fatal, or -1 if not set).
func (*Backend) NewSharedBuffer ¶
func (*Backend) NumDevices ¶
func (*Backend) SetKeepModelProto ¶
SetKeepModelProto controls whether compiled Executable instances retain the graph *onnx.ModelProto. When set to true, executables compiled by this backend store their ONNX ModelProto struct, allowing the computation graph to be exported via SaveModel.
func (*Backend) Version ¶ added in v0.1.4
Version returns the version of the underlying ONNX Runtime engine.
func (*Backend) WebVersion ¶ added in v0.1.4
WebVersion returns the configured web version string (e.g. "dev", "@latest", "1.27", or "").
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
onnx_printer
command
Package main provides the onnx_printer tool to pretty-print ONNX model files.
|
Package main provides the onnx_printer tool to pretty-print ONNX model files. |
|
onnxruntime_web_installer
command
|
|
|
onnxruntime_installer
module
|
|
|
internal
|
|
|
cmd/update_c_ort
command
|
|
|
cmd/update_protos
command
|
|
|
support
|
|
|
protos
Package protos contains the protobuf generated code for the ONNX format.
|
Package protos contains the protobuf generated code for the ONNX format. |