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 with go 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 .onnx models, and support for exporting trained GoMLX models to the standard .onnx file format.
  • Cons: Native desktop/server builds require CGo/C++ dependencies for ONNX Runtime (linux/amd64 and windows/amd64).

Configuration Options

Configure via GOMLX_BACKEND="onnx:<options>" or compute.NewWithConfig(...):

  • cpu: Forces CPU execution.
  • cuda (or gpu): Forces CUDA GPU execution via the ONNX Runtime CUDA Execution Provider.
  • migraphx (or rocm, 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:
    go run github.com/gomlx/compute-onnx/cmd/onnxruntime_installer -migraphx
    
    Notes / Limitations:
    • Only float32, int32, and int64 graphs are supported.
    • Models with scalar (0-dimensional) inputs fail (upstream issue).
    • Buffers are currently transferred back to CPU (host), which makes training slower.
  • 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 via GOMLX_MIGRAPHX_CACHE_DIR.
  • <path/to/libonnxruntime.so>: Explicit path to the ONNX Runtime shared library binary (.so, .dylib, or .dll), bypassing ONNXRUNTIME_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 to 1 to avoid thread oversubscription.
  • inter_op_num_threads=<int>: Number of threads to parallelize execution across independent operators (only effective with execution_mode=parallel).
  • execution_mode=<parallel|sequential>: Controls whether independent operators execute sequentially or in parallel. Can also be specified as standalone parallel or sequential.
  • cpu_mem_arena=<bool>: Enables/disables ONNX Runtime’s CPU memory arena allocator (default: true). Disabling (cpu_mem_arena=false or no_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> (or disable_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 compiled Executable (default: 8 on CPU, 1 on 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:migraphx
  • GOMLX_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 bypasses ONNXRUNTIME_SHARED_LIBRARY_PATH), or by setting the ONNXRUNTIME_SHARED_LIBRARY_PATH environment variable.
  • Disabling Auto-Installation: Set environment variable GOMLX_NO_AUTO_INSTALL=1 or call onnxbackend.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 -migraphx to 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 locate rocminfo and 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 the migraphx_cache_dir configuration 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, set GOMLX_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 a klog notification.

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 .onnx file.
    • onnx.Save(backend, exec, writer, inputShapes, inputNames, outputNames): Exports the ONNX model to an io.Writer.
    • onnx.LoadFromFile(backend, filePath) / onnx.Load(backend, reader): Loads an .onnx model into an executable for inference within GoMLX.
    • onnx.IsONNX(backend): Returns true if the provided compute.Backend is an ONNX backend instance (*onnxbackend.Backend).
  • Dynamic Axes: Supports dynamic input dimensions (such as variable batch sizes) using exec.WithDynamicAxes(...) and shapes.MakeDynamic(...).
  • Example: See the save_onnx.go demo 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 (or gpu): Hardware-accelerated GPU shader execution via WebGPU (best for large vision/transformer models and parallel batches).
    • wasm (or cpu): 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 webgpu if present, otherwise falling back to wasm CPU.
  • Zero-Config Script Loading: If ort.min.js is 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 .onnx model file directly in the terminal, use the onnx_printer utility in github.com/gomlx/compute-onnx/cmd/onnx_printer:
    go run github.com/gomlx/compute-onnx/cmd/onnx_printer path/to/model.onnx
    
    It formats tensor shapes using GoMLX shapes.Shape (including dynamic dimension names), prints operations on a single line per op, and truncates large constant tensors (use -max_items or -n to control element limit).
  • Graphical Visualization: For interactive graphical diagram visualization of ONNX computation graphs, open your .onnx model file using Netron.
Last updated December 1, 2026