ONNX Runtime Backend ("onnx")
Execute GoMLX graphs via ONNX Runtime across CPU, CUDA, ROCm/MIGraphX, and WebAssembly/WebGPU, or export trained models to .onnx files.
Importing
- Included by default in
backends/default? No (requires--tags=onnx) — included via_ "github.com/gomlx/gomlx/backends/default"only when building withgo build --tags=onnx(linux/amd64). - Standalone blank import (links the ONNX Runtime backend directly without build tags):
import _ "github.com/gomlx/compute-onnx"
Overview
The "onnx" backend uses ONNX Runtime (ORT) to execute GoMLX computation graphs on Linux and Windows (amd64), as well as in web browsers via WebAssembly. It is implemented in github.com/gomlx/compute-onnx.
- Pros: Interoperability with the ONNX ecosystem, native dynamic shapes, browser execution via WebGPU/WASM, ability to execute
.onnxmodels, and support for exporting trained GoMLX models to the standard.onnxfile format. - Cons: Native desktop/server builds require CGo/C++ dependencies for ONNX Runtime (
linux/amd64andwindows/amd64).
Configuration Options
Configure via GOMLX_BACKEND="onnx:<options>" or compute.NewWithConfig(...):
cpu: Forces CPU execution.cuda(orgpu): Forces CUDA GPU execution via the ONNX Runtime CUDA Execution Provider.migraphx(orrocm,amd) (Experimental): Forces AMD GPU execution via the ONNX Runtime MIGraphX Execution Provider. Requires ROCm and MIGraphX to be installed (sudo apt install migraphx migraphx-dev half). If no ORT library with the MIGraphX provider is found, one is automatically installed from AMD’s manylinux wheels matching the local ROCm version — it can also be installed manually with:Notes / Limitations:go run github.com/gomlx/compute-onnx/cmd/onnxruntime_installer -migraphx- Only
float32,int32, andint64graphs are supported. - Models with scalar (0-dimensional) inputs fail (upstream issue).
- Buffers are currently transferred back to CPU (host), which makes training slower.
- Only
migraphx_cache_dir=<path>: Directory where the MIGraphX compiled program (.mxr) for each model is cached, skipping expensive graph compilation on subsequent runs. Can also be set viaGOMLX_MIGRAPHX_CACHE_DIR.<path/to/libonnxruntime.so>: Explicit path to the ONNX Runtime shared library binary (.so,.dylib, or.dll), bypassingONNXRUNTIME_SHARED_LIBRARY_PATH.log=<level>: Sets internal logging severity level (0=Error,1=Warning,2=Info,3=Verbose).intra_op_num_threads=<int>: Number of threads to parallelize execution within an operator (default:0= all CPU cores). When running multiple concurrent goroutines/workers, set this to1to avoid thread oversubscription.inter_op_num_threads=<int>: Number of threads to parallelize execution across independent operators (only effective withexecution_mode=parallel).execution_mode=<parallel|sequential>: Controls whether independent operators execute sequentially or in parallel. Can also be specified as standaloneparallelorsequential.cpu_mem_arena=<bool>: Enables/disables ONNX Runtime’s CPU memory arena allocator (default:true). Disabling (cpu_mem_arena=falseorno_cpu_mem_arena) avoids allocator lock contention across parallel workers.mem_pattern=<bool>: Enables/disables memory pattern optimization (default:true; sequential mode only).graph_optimization_level=<0|1|2|3|99>(ordisable_all,basic,extended,all): Controls the graph optimization level applied by ONNX Runtime.session_clones=<int>: Maximum number of concurrent ONNX Runtime session clones pooled per compiledExecutable(default:8on CPU,1on GPU). Clones are allocated on-demand as concurrent goroutines execute, eliminating lock contention while avoiding memory overhead for single-threaded usage.- Default (empty): Auto-detects if an NVIDIA GPU is available and defaults to CUDA if present, then checks for a discrete AMD GPU (ROCm/MIGraphX), otherwise falling back to CPU.
Examples
GOMLX_BACKEND="onnx:cuda,log=2"GOMLX_BACKEND=onnx:migraphxGOMLX_BACKEND="onnx:cpu,intra_op_num_threads=1,inter_op_num_threads=1,cpu_mem_arena=false,execution_mode=parallel"GOMLX_BACKEND="onnx:/path/to/libonnxruntime.so"
Auto-Installation & Environment Variables
ONNX Runtime Auto-Installation
The ONNX Runtime backend includes an auto-installer. At startup, if the ONNX Runtime shared library (libonnxruntime.so on Linux, libonnxruntime.dylib on macOS, onnxruntime.dll on Windows) is not found, it automatically downloads and extracts the official ONNX Runtime binaries locally into:
- Linux:
~/.local/lib/onnxruntime/(or~/.local/lib/onnxruntime-migraphx/for MIGraphX) - macOS:
~/Library/Application Support/onnxruntime/ - Windows:
~\AppData\Local\onnxruntime\
Custom Library Path & Disabling Auto-Installation
- Custom Library Path: Specify an explicit shared library location by passing a path in the configuration string (e.g.,
GOMLX_BACKEND=onnx:/path/to/libonnxruntime.so, which bypassesONNXRUNTIME_SHARED_LIBRARY_PATH), or by setting theONNXRUNTIME_SHARED_LIBRARY_PATHenvironment variable. - Disabling Auto-Installation: Set environment variable
GOMLX_NO_AUTO_INSTALL=1or callonnxbackend.EnableAutoInstall(false)programmatically before initializing the backend to prevent automatic downloads (ideal for offline environments or production Docker builds). - Standalone Installer Utility: Pre-install libraries using the CLI tool in
github.com/gomlx/compute-onnx/cmd/onnxruntime_installer(pass-migraphxto install the ROCm/MIGraphX build).
AMD ROCm / MIGraphX Environment Variables (Experimental)
The MIGraphX execution provider relies on a local ROCm installation:
ROCM_PATH: Directory where ROCm is installed (defaults to/opt/rocm). Used to locaterocminfoand HIP/MIGraphX libraries when auto-detecting AMD GPUs and ROCm versions.GOMLX_MIGRAPHX_CACHE_DIR: Directory where MIGraphX compiled programs (.mxr) are cached, skipping expensive graph compilation on subsequent runs. Equivalent to themigraphx_cache_dirconfiguration key (e.g.,GOMLX_BACKEND=onnx:migraphx,migraphx_cache_dir=/tmp/mxr); an empty value disables caching.
Debugging & Saving Models on Compilation Failure
GOMLX_ONNX_SAVE_ON_FAILURE: If graph compilation or session creation fails, setGOMLX_ONNX_SAVE_ON_FAILURE=/path/to/failed_model.onnx. When set, the backend writes the serialized ONNX model protobuf to that file path for inspection and prints aklognotification.
Exporting / Saving Models to .onnx Format
With the onnx backend enabled, you can save trained GoMLX models to standard .onnx files. These files can then be loaded and executed with ONNX Runtime in GoMLX or deployed in other languages and inference engines.
- Package:
github.com/gomlx/gomlx/ml/model/onnx(protected by build tag//go:build onnx). - Key Functions:
onnx.SaveToFile(backend, exec, filePath, inputShapes, inputNames, outputNames): Exports the computation graph and model parameters to an.onnxfile.onnx.Save(backend, exec, writer, inputShapes, inputNames, outputNames): Exports the ONNX model to anio.Writer.onnx.LoadFromFile(backend, filePath)/onnx.Load(backend, reader): Loads an.onnxmodel into an executable for inference within GoMLX.onnx.IsONNX(backend): Returnstrueif the providedcompute.Backendis an ONNX backend instance (*onnxbackend.Backend).
- Dynamic Axes: Supports dynamic input dimensions (such as variable batch sizes) using
exec.WithDynamicAxes(...)andshapes.MakeDynamic(...). - Example: See the
save_onnx.godemo in the UCI-Adult example (build with-tags=onnx).
WebAssembly / Browser Execution (ONNX Runtime Web)
The onnx backend also supports compiling to WebAssembly (GOOS=js GOARCH=wasm) and executing inside web browsers via ONNX Runtime Web.
- Supported Execution Providers:
webgpu(orgpu): Hardware-accelerated GPU shader execution via WebGPU (best for large vision/transformer models and parallel batches).wasm(orcpu): High-speed CPU WebAssembly execution using SIMD instructions (best latency for small models and single-sample loops).webnn: Hardware NPU/GPU acceleration via the experimental Web Neural Network API in Chromium.
- Auto-Detection: Automatically detects WebGPU hardware availability at startup and defaults to
webgpuif present, otherwise falling back towasmCPU. - Zero-Config Script Loading: If
ort.min.jsis not embedded in the page, the backend automatically injects it from the official CDN at runtime.
Inspecting & Visualizing .onnx Files
- CLI Printer (
onnx_printer): To inspect the contents, shapes, initializers, and operations of an.onnxmodel file directly in the terminal, use theonnx_printerutility ingithub.com/gomlx/compute-onnx/cmd/onnx_printer:It formats tensor shapes using GoMLXgo run github.com/gomlx/compute-onnx/cmd/onnx_printer path/to/model.onnxshapes.Shape(including dynamic dimension names), prints operations on a single line per op, and truncates large constant tensors (use-max_itemsor-nto control element limit). - Graphical Visualization: For interactive graphical diagram visualization of ONNX computation graphs, open your
.onnxmodel file using Netron.