onnxbackend

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 14, 2026 License: Apache-2.0 Imports: 29 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

compute-onnx

Documentation Sponsor GoMLX

🚧🏗️ EXPERIMENTAL 🏗️🚧

ONNX Runtime based compute backend for GoMLX.

It allows GoMLX models to be executed via ONNX Runtime using either CPU or CUDA (NVIDIA GPU).

It supports dynamic shapes and exporting models to .onnx files.

Example Usage

To run the Adult dataset demo with the ONNX backend:

GOMLX_BACKEND=onnx go run -tags=onnx github.com/gomlx/gomlx/examples/adult/demo

Or targeting a specific accelerator (e.g. CUDA):

GOMLX_BACKEND=onnx:cuda go run -tags=onnx github.com/gomlx/gomlx/examples/adult/demo

Backend Options & Configuration

Configuration can be specified in the GOMLX_BACKEND environment variable using onnx:<options> or onnxruntime:<options> (comma-separated).

Accelerator Selection
  • cpu: Force CPU execution.
    GOMLX_BACKEND=onnx:cpu
    
  • cuda / gpu: Force CUDA GPU execution (uses ONNX Runtime CUDA Execution Provider via OrtIoBinding).
    GOMLX_BACKEND=onnx:cuda
    
  • empty (default): Automatically detects if an NVIDIA GPU is present via nvidia-smi and defaults to CUDA if available, otherwise falling back to CPU.
    GOMLX_BACKEND=onnx
    
Save Model To ONNX

This allows one to export GOMLX trained (or fine-tuned) models to ONNX.

See an example in UCI-Adult demo. If you have a pre-trained file in a directory called base:

GOMLX_BACKEND=onnx go run -tags=onnx ./examples/adult/demo/ -checkpoint "base" -save_onnx="/tmp/a.onnx" -vmodule=save_onnx=1
Logging & Verbosity
  • Backend Log Level (log=<level>): Configures ONNX Runtime's internal logging severity level.

    • log=0: Errors only (severity level 3 / ERROR)
    • log=1: Warnings (severity level 2 / WARNING)
    • log=2: Informational (severity level 1 / INFO)
    • log=3: Verbose (severity level 0 / VERBOSE)

    Example:

    GOMLX_BACKEND="onnx:cuda,log=2"
    
  • Execution Timing Log (-vmodule=executable=1): Enables per-step execution timing breakdown printed via klog using humanize.Duration.

    Example:

    GOMLX_BACKEND=onnx:cuda go run -tags=onnx github.com/gomlx/gomlx/examples/adult/demo -vmodule=executable=1
    

Documentation

Index

Constants

View Source
const (
	BackendName = "onnxruntime"
)
View Source
const NoAutoInstallEnv = "GOMLX_NO_AUTO_INSTALL"

Variables

This section is empty.

Functions

func HasNvidiaGPU

func HasNvidiaGPU() bool

HasNvidiaGPU tries to guess if there is an actual Nvidia GPU installed.

func IsSupportedPlatform

func IsSupportedPlatform() bool

IsSupportedPlatform returns true if the host OS and CPU architecture are supported by ONNX Runtime binaries.

func LoadModel

func LoadModel(backend compute.Backend, r io.Reader) (compute.Executable, error)

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 New

func New(config string) (compute.Backend, error)

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 a ONNX Runtime backed compute.Backend.

func (*Backend) BufferFromFlatData

func (b *Backend) BufferFromFlatData(deviceNum compute.DeviceNum, flat any, shape shapes.Shape) (compute.Buffer, error)

func (*Backend) Builder

func (b *Backend) Builder(name string) compute.Builder

func (*Backend) Capabilities

func (b *Backend) Capabilities() compute.Capabilities

func (*Backend) Description

func (b *Backend) Description() string

func (*Backend) DeviceDescription

func (b *Backend) DeviceDescription(deviceNum compute.DeviceNum) string

func (*Backend) Finalize

func (b *Backend) Finalize()

func (*Backend) HasSharedBuffers

func (b *Backend) HasSharedBuffers() bool

func (*Backend) IsFinalized

func (b *Backend) IsFinalized() bool

func (*Backend) KeepModelProto

func (b *Backend) KeepModelProto() bool

KeepModelProto returns whether compiled Executable instances retain their graph *onnx.ModelProto.

func (*Backend) Name

func (b *Backend) Name() string

func (*Backend) NewSharedBuffer

func (b *Backend) NewSharedBuffer(deviceNum compute.DeviceNum, shape shapes.Shape) (compute.Buffer, any, error)

func (*Backend) NumDevices

func (b *Backend) NumDevices() int

func (*Backend) SetKeepModelProto

func (b *Backend) SetKeepModelProto(keep bool)

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) String

func (b *Backend) String() string

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

Buffer implements compute.Buffer for ONNX Runtime.

func (*Buffer) Backend

func (b *Buffer) Backend() compute.Backend

func (*Buffer) CopyToDevice

func (b *Buffer) CopyToDevice(deviceNum compute.DeviceNum) (compute.Buffer, error)

func (*Buffer) Data

func (b *Buffer) Data() (flat any, err error)

func (*Buffer) DeviceNum

func (b *Buffer) DeviceNum() (compute.DeviceNum, error)

func (*Buffer) Finalize

func (b *Buffer) Finalize() error

func (*Buffer) Shape

func (b *Buffer) Shape() (shapes.Shape, error)

func (*Buffer) ToFlatData

func (b *Buffer) ToFlatData(flat any) error

type Builder

type Builder struct {
	notimplemented.Builder
	// contains filtered or unexported fields
}

func NewBuilder

func NewBuilder(name string, backend *Backend) *Builder

func (*Builder) Compile

func (b *Builder) Compile() (compute.Executable, error)

func (*Builder) DeviceAssignment

func (b *Builder) DeviceAssignment(devices ...compute.DeviceNum) error

func (*Builder) Main

func (b *Builder) Main() compute.Function

func (*Builder) Name

func (b *Builder) Name() string

func (*Builder) NewFunction

func (b *Builder) NewFunction(name string) (compute.Function, error)

func (*Builder) OpShape

func (b *Builder) OpShape(op compute.Value) (shapes.Shape, error)

type Executable

type Executable struct {
	// contains filtered or unexported fields
}

func (*Executable) Execute

func (e *Executable) Execute(inputs []compute.Buffer, donate []bool, defaultDevice compute.DeviceNum) ([]compute.Buffer, error)

func (*Executable) Finalize

func (e *Executable) Finalize()

func (*Executable) Inputs

func (e *Executable) Inputs() (names []string, inputShapes []shapes.Shape)

func (*Executable) ModelProto

func (e *Executable) ModelProto() *onnx.ModelProto

ModelProto returns the ONNX ModelProto struct if Backend.KeepModelProto was enabled during compilation, or nil otherwise.

func (*Executable) Outputs

func (e *Executable) Outputs() (outputShapes []shapes.Shape)

type Function

type Function struct {
	notimplemented.Function
	// contains filtered or unexported fields
}

func NewFunction

func NewFunction(name string, builder *Builder) *Function

func (*Function) Abs

func (f *Function) Abs(x compute.Value) (compute.Value, error)

func (*Function) Add

func (f *Function) Add(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) ArgMinMax

func (f *Function) ArgMinMax(x compute.Value, axis int, outputDType dtypes.DType, isMin bool) (compute.Value, error)

func (*Function) BitwiseAnd

func (f *Function) BitwiseAnd(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) BitwiseOr

func (f *Function) BitwiseOr(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) BitwiseXor

func (f *Function) BitwiseXor(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) BroadcastInDim

func (f *Function) BroadcastInDim(x compute.Value, outputShape shapes.Shape, broadcastAxes []int) (compute.Value, error)

func (*Function) Builder

func (f *Function) Builder() compute.Builder

func (*Function) Ceil

func (f *Function) Ceil(x compute.Value) (compute.Value, error)

func (*Function) Concatenate

func (f *Function) Concatenate(axis int, inputs ...compute.Value) (compute.Value, error)

func (*Function) Constant

func (f *Function) Constant(flat any, dims ...int) (compute.Value, error)

func (*Function) ConvGeneral

func (f *Function) ConvGeneral(input, kernel compute.Value, axes compute.ConvolveAxesConfig, strides []int, paddings [][2]int, inputDilations []int, kernelDilations []int, channelGroupCount int, batchGroupCount int) (compute.Value, error)

func (*Function) ConvertDType

func (f *Function) ConvertDType(operand compute.Value, targetDType dtypes.DType) (compute.Value, error)

func (*Function) Cos

func (f *Function) Cos(x compute.Value) (compute.Value, error)

func (*Function) Div

func (f *Function) Div(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) DotGeneral

func (f *Function) DotGeneral(
	lhs compute.Value,
	lhsContractingAxes []int,
	lhsBatchAxes []int,
	rhs compute.Value,
	rhsContractingAxes []int,
	rhsBatchAxes []int,
	config compute.DotGeneralConfig,
) (compute.Value, error)

DotGeneral performs a general dot product (matrix multiplication) of lhs and rhs. It maps the generalized contracting and batching axes of XLA semantics to ONNX Einsum.

func (*Function) DynamicDimensionSize

func (f *Function) DynamicDimensionSize(operand compute.Value, axis int) (compute.Value, error)

func (*Function) DynamicReshape

func (f *Function) DynamicReshape(operand compute.Value, dimensions ...compute.DynamicDimensionSpec) (compute.Value, error)

func (*Function) DynamicShape

func (f *Function) DynamicShape(operand compute.Value) (compute.Value, error)

func (*Function) DynamicSlice

func (f *Function) DynamicSlice(operand compute.Value, startIndices []compute.Value, sliceDims []int) (compute.Value, error)

func (*Function) DynamicUpdateSlice

func (f *Function) DynamicUpdateSlice(operand, update compute.Value, startIndices []compute.Value) (compute.Value, error)

func (*Function) Equal

func (f *Function) Equal(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Erf

func (f *Function) Erf(x compute.Value) (compute.Value, error)

func (*Function) Exp

func (f *Function) Exp(x compute.Value) (compute.Value, error)

func (*Function) Floor

func (f *Function) Floor(x compute.Value) (compute.Value, error)

func (*Function) FusedAttentionQKVProjection

func (f *Function) FusedAttentionQKVProjection(
	x, wQKV, biasQ, biasK, biasV compute.Value,
	queryDim, keyValueDim int) (query, key, value compute.Value, err error)

FusedAttentionQKVProjection performs fused Query-Key-Value projection.

func (*Function) FusedDense

func (f *Function) FusedDense(x, weight, bias compute.Value, options compute.DenseConfig) (compute.Value, error)

FusedDense performs fused matmul + optional bias + optional activation.

func (*Function) FusedGelu

func (f *Function) FusedGelu(x compute.Value, exact bool) (compute.Value, error)

FusedGelu computes Gaussian Error Linear Unit activation using ONNX Gelu (opset 20+).

func (*Function) FusedLayerNorm

func (f *Function) FusedLayerNorm(x compute.Value, axes []int, epsilon float64, gamma, beta compute.Value) (compute.Value, error)

FusedLayerNorm applies layer normalization over specified axes using ONNX LayerNormalization (opset 17+).

func (*Function) FusedQuantizedDense

func (f *Function) FusedQuantizedDense(x, weights, bias compute.Value, weightsQuantization *compute.Quantization, activation compute.ActivationType) (compute.Value, error)

FusedQuantizedDense performs fused dequantization + matmul + optional bias + optional activation.

func (*Function) FusedScaledDotProductAttention

func (f *Function) FusedScaledDotProductAttention(
	query, key, value compute.Value,
	axesLayout compute.AttentionAxesLayout,
	options *compute.ScaledDotProductAttentionConfig) (output compute.Value, statesForVJP []compute.Value, err error)

FusedScaledDotProductAttention computes multi-head scaled dot-product attention.

func (*Function) FusedScaledDotProductAttentionVJP

func (f *Function) FusedScaledDotProductAttentionVJP(
	query, key, value compute.Value,
	axesLayout compute.AttentionAxesLayout,
	options *compute.ScaledDotProductAttentionConfig,
	output compute.Value, statesForVJP []compute.Value, dOutput compute.Value) (dQuery, dKey, dValue compute.Value, err error)

FusedScaledDotProductAttentionVJP computes gradients of FusedScaledDotProductAttention.

func (*Function) FusedSoftmax

func (f *Function) FusedSoftmax(x compute.Value, axis int) (compute.Value, error)

FusedSoftmax computes softmax along the specified axis using ONNX Softmax.

func (*Function) Gather

func (f *Function) Gather(
	operand compute.Value,
	startIndices compute.Value,
	indexVectorAxis int,
	offsetOutputAxes []int,
	collapsedSliceAxes []int,
	startIndexMap []int,
	sliceSizes []int,
	indicesAreSorted bool,
) (compute.Value, error)

Gather gathers slices from operand using coordinates specified by startIndices. It maps the generalized XLA Gather semantics to ONNX GatherND, Reshape, and Transpose.

func (*Function) GreaterOrEqual

func (f *Function) GreaterOrEqual(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) GreaterThan

func (f *Function) GreaterThan(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Identity

func (f *Function) Identity(x compute.Value) (compute.Value, error)

func (*Function) Iota

func (f *Function) Iota(shape shapes.Shape, iotaAxis int) (compute.Value, error)

func (*Function) LessOrEqual

func (f *Function) LessOrEqual(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) LessThan

func (f *Function) LessThan(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Log

func (f *Function) Log(x compute.Value) (compute.Value, error)

func (*Function) Log1p

func (f *Function) Log1p(x compute.Value) (compute.Value, error)

func (*Function) LogicalAnd

func (f *Function) LogicalAnd(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) LogicalNot

func (f *Function) LogicalNot(x compute.Value) (compute.Value, error)

func (*Function) LogicalOr

func (f *Function) LogicalOr(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) LogicalXor

func (f *Function) LogicalXor(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Logistic

func (f *Function) Logistic(x compute.Value) (compute.Value, error)

func (*Function) Max

func (f *Function) Max(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Min

func (f *Function) Min(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Mul

func (f *Function) Mul(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Name

func (f *Function) Name() string

func (*Function) Neg

func (f *Function) Neg(x compute.Value) (compute.Value, error)

func (*Function) NotEqual

func (f *Function) NotEqual(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Parameter

func (f *Function) Parameter(name string, shape shapes.Shape, spec *compute.ShardingSpec) (compute.Value, error)

func (*Function) Parent

func (f *Function) Parent() compute.Function

func (*Function) Pow

func (f *Function) Pow(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) QuantizedEmbeddingLookup

func (f *Function) QuantizedEmbeddingLookup(data, indices compute.Value, dataQuantization *compute.Quantization) (compute.Value, error)

QuantizedEmbeddingLookup performs a quantized embedding lookup with on-the-fly dequantization.

func (*Function) RNGBitGenerator

func (f *Function) RNGBitGenerator(state compute.Value, shape shapes.Shape) (newState compute.Value, values compute.Value, err error)

RNGBitGenerator generates a tensor of the requested shape filled with random bits. It receives a state of shape [3]uint64 containing [seed/key, counter_low, counter_high]. It implements SplitMix64 PRNG algorithm inside the ONNX graph.

func (*Function) Reduce

func (f *Function) Reduce(x compute.Value, opType compute.OpType, axes []int, keepDims bool) (compute.Value, error)

func (*Function) ReduceLogical

func (f *Function) ReduceLogical(x compute.Value, opType compute.OpType, axes []int, keepDims bool) (compute.Value, error)

func (*Function) ReduceLogicalAnd

func (f *Function) ReduceLogicalAnd(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceLogicalOr

func (f *Function) ReduceLogicalOr(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceLogicalXor

func (f *Function) ReduceLogicalXor(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceMax

func (f *Function) ReduceMax(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceMin

func (f *Function) ReduceMin(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceProduct

func (f *Function) ReduceProduct(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceSum

func (f *Function) ReduceSum(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) ReduceWindow

func (f *Function) ReduceWindow(
	operand compute.Value,
	reductionType compute.ReduceOpType,
	windowDimensions, strides, inputDilations, windowDilations []int,
	paddings [][2]int,
) (compute.Value, error)

func (*Function) Rem

func (f *Function) Rem(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Reshape

func (f *Function) Reshape(x compute.Value, newDimensions ...int) (compute.Value, error)

func (*Function) Return

func (f *Function) Return(outputs []compute.Value, shardings []*compute.ShardingSpec) error

func (*Function) Reverse

func (f *Function) Reverse(x compute.Value, axes ...int) (compute.Value, error)

func (*Function) Round

func (f *Function) Round(x compute.Value) (compute.Value, error)

func (*Function) ScatterMax

func (f *Function) ScatterMax(
	operand, scatterIndices, updates compute.Value,
	indexVectorAxis int,
	updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
	indicesAreSorted, uniqueIndices bool,
) (compute.Value, error)

func (*Function) ScatterMin

func (f *Function) ScatterMin(
	operand, scatterIndices, updates compute.Value,
	indexVectorAxis int,
	updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
	indicesAreSorted, uniqueIndices bool,
) (compute.Value, error)

func (*Function) ScatterSum

func (f *Function) ScatterSum(
	operand, scatterIndices, updates compute.Value,
	indexVectorAxis int,
	updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int,
	indicesAreSorted, uniqueIndices bool,
) (compute.Value, error)

func (*Function) SchedulingBarrier

func (f *Function) SchedulingBarrier(operand compute.Value, dependencies ...compute.Value) (compute.Value, error)

SchedulingBarrier introduces a scheduling barrier. Returned value is identity to the operand, but it is guaranteed to depend on all the dependencies.

Since ONNX Runtime doesn't natively support a scheduling barrier op, we "hack" it by means of a no-op: taking a scalar of each dependency, multiplying by 0, and adding them to the operand.

func (*Function) SelectAndScatterMax

func (f *Function) SelectAndScatterMax(operand compute.Value, source compute.Value, windowDimensions []int, windowStrides []int, paddings [][2]int) (compute.Value, error)

func (*Function) Shape

func (f *Function) Shape(v compute.Value) (shapes.Shape, error)

func (*Function) ShiftLeft

func (f *Function) ShiftLeft(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) ShiftRightLogical

func (f *Function) ShiftRightLogical(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Sign

func (f *Function) Sign(x compute.Value) (compute.Value, error)

func (*Function) Sin

func (f *Function) Sin(x compute.Value) (compute.Value, error)

func (*Function) Slice

func (f *Function) Slice(x compute.Value, start []int, limit []int, stride []int) (compute.Value, error)

func (*Function) Sqrt

func (f *Function) Sqrt(x compute.Value) (compute.Value, error)

func (*Function) Sub

func (f *Function) Sub(lhs, rhs compute.Value) (compute.Value, error)

func (*Function) Tanh

func (f *Function) Tanh(x compute.Value) (compute.Value, error)

func (*Function) Transpose

func (f *Function) Transpose(x compute.Value, permutation ...int) (compute.Value, error)

func (*Function) Where

func (f *Function) Where(condition compute.Value, onTrue compute.Value, onFalse compute.Value) (compute.Value, error)

type Node

type Node struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis
cmd
internal
ort
protos
Package protos contains the protobuf generated code for the ONNX format.
Package protos contains the protobuf generated code for the ONNX format.
support

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL