onnx

package
v0.7.16 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package onnx provides ONNX model import/export functionality.

ONNX (Open Neural Network Exchange) is an open format for representing deep learning models. This package implements a hand-written protobuf parser for .onnx files without external dependencies.

Key components:

  • ModelProto: Top-level ONNX model structure with metadata and graph
  • GraphProto: Computation graph with nodes, inputs, outputs, and initializers
  • NodeProto: Single operation in the graph (e.g., Conv, MatMul, Relu)
  • TensorProto: Weight/initializer tensor with data and shape
  • ValueInfoProto: Input/output tensor type information

Supported data types:

  • float32, float64 (primary ML types)
  • int8, int16, int32, int64 (integer types)
  • uint8, uint16, uint32, uint64 (unsigned types)
  • bool (boolean type)

Example usage:

// Parse ONNX file
model, err := onnx.ParseFile("resnet50.onnx")
if err != nil {
    log.Fatal(err)
}

// Inspect model
fmt.Printf("Model: %s (version %d)\n", model.ProducerName, model.ModelVersion)
fmt.Printf("Graph: %s with %d nodes\n", model.Graph.Name, len(model.Graph.Nodes))

// Iterate over operations
for _, node := range model.Graph.Nodes {
    fmt.Printf("Op: %s (type: %s)\n", node.Name, node.OpType)
}

Index

Constants

View Source
const (
	TensorProtoUndefined  = 0
	TensorProtoFloat      = 1  // float32
	TensorProtoUint8      = 2  // uint8
	TensorProtoInt8       = 3  // int8
	TensorProtoUint16     = 4  // uint16
	TensorProtoInt16      = 5  // int16
	TensorProtoInt32      = 6  // int32
	TensorProtoInt64      = 7  // int64
	TensorProtoString     = 8  // string
	TensorProtoBool       = 9  // bool
	TensorProtoFloat16    = 10 // float16
	TensorProtoDouble     = 11 // float64
	TensorProtoUint32     = 12 // uint32
	TensorProtoUint64     = 13 // uint64
	TensorProtoComplex64  = 14 // complex64
	TensorProtoComplex128 = 15 // complex128
	TensorProtoBfloat16   = 16 // bfloat16
)

ONNX data types (TensorProto.DataType).

View Source
const (
	AttributeProtoUndefined = 0
	AttributeProtoFloat     = 1  // FLOAT
	AttributeProtoInt       = 2  // INT
	AttributeProtoString    = 3  // STRING
	AttributeProtoTensor    = 4  // TENSOR
	AttributeProtoGraph     = 5  // GRAPH
	AttributeProtoFloats    = 6  // FLOATS
	AttributeProtoInts      = 7  // INTS
	AttributeProtoStrings   = 8  // STRINGS
	AttributeProtoTensors   = 9  // TENSORS
	AttributeProtoGraphs    = 10 // GRAPHS
)

ONNX attribute types (AttributeProto.Type).

Variables

This section is empty.

Functions

func ListSupportedOps

func ListSupportedOps() []string

ListSupportedOps returns all supported ONNX operators.

Types

type AttributeProto

type AttributeProto struct {
	Name      string        // Attribute name
	Type      int32         // Attribute type
	F         float32       // FLOAT value
	I         int64         // INT value
	S         []byte        // STRING value
	T         *TensorProto  // TENSOR value
	G         *GraphProto   // GRAPH value
	Floats    []float32     // FLOATS array
	Ints      []int64       // INTS array
	Strings   [][]byte      // STRINGS array
	Tensors   []TensorProto // TENSORS array
	Graphs    []GraphProto  // GRAPHS array
	DocString string        // Description
}

AttributeProto represents node attributes.

type DimensionProto

type DimensionProto struct {
	DimValue int64  // Static dimension value (e.g., 224 for image size)
	DimParam string // Dynamic dimension name (e.g., "batch_size")
}

DimensionProto describes a single dimension.

type GraphProto

type GraphProto struct {
	Name         string           // Graph name
	Nodes        []NodeProto      // Operation nodes
	Inputs       []ValueInfoProto // Graph inputs
	Outputs      []ValueInfoProto // Graph outputs
	Initializers []TensorProto    // Weight tensors
	DocString    string           // Graph description
	ValueInfo    []ValueInfoProto // Intermediate tensor info
}

GraphProto represents the computation graph.

type LoadOptions

type LoadOptions struct {
	// StrictMode fails on unsupported operators (default: false = skip with warning).
	StrictMode bool

	// CustomOps provides custom operator handlers.
	CustomOps map[string]operators.OpHandler
}

LoadOptions configures model loading behavior.

func DefaultLoadOptions

func DefaultLoadOptions() LoadOptions

DefaultLoadOptions returns default loading options.

type Model

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

Model represents a loaded ONNX model ready for inference. It executes the computation graph using the provided backend.

func Load

func Load(path string, backend tensor.Backend, opts ...LoadOptions) (*Model, error)

Load loads an ONNX model from file and prepares it for inference. The backend is used for tensor operations during inference.

Example:

model, err := onnx.Load("resnet50.onnx", backend)
if err != nil {
    log.Fatal(err)
}
output, err := model.Forward(input)

func LoadFromBytes

func LoadFromBytes(data []byte, backend tensor.Backend, opts ...LoadOptions) (*Model, error)

LoadFromBytes loads an ONNX model from bytes.

func LoadFromProto

func LoadFromProto(proto *ModelProto, backend tensor.Backend, opt LoadOptions) (*Model, error)

LoadFromProto loads a model from parsed ModelProto.

func (*Model) Forward

func (m *Model) Forward(input *tensor.RawTensor) (*tensor.RawTensor, error)

Forward runs inference with a single input tensor. For models with multiple inputs, use ForwardNamed.

func (*Model) ForwardNamed

func (m *Model) ForwardNamed(inputs map[string]*tensor.RawTensor) (map[string]*tensor.RawTensor, error)

ForwardNamed runs inference with named inputs. Returns a map of output name to tensor.

func (*Model) InputNames

func (m *Model) InputNames() []string

InputNames returns the names of model inputs.

func (*Model) Metadata

func (m *Model) Metadata() map[string]string

Metadata returns model metadata as key-value pairs.

func (*Model) OpsetVersion

func (m *Model) OpsetVersion() int64

OpsetVersion returns the ONNX opset version.

func (*Model) OutputNames

func (m *Model) OutputNames() []string

OutputNames returns the names of model outputs.

type ModelInfo

type ModelInfo struct {
	IRVersion       int64
	OpsetVersion    int64
	ProducerName    string
	ProducerVersion string
	InputNames      []string
	OutputNames     []string
	NodeCount       int
	WeightCount     int
}

ModelInfo contains basic information about an ONNX model without fully loading it.

func GetModelInfo

func GetModelInfo(path string) (*ModelInfo, error)

GetModelInfo extracts basic info from an ONNX file.

type ModelProto

type ModelProto struct {
	IRVersion       int64               // IR version (e.g., 7, 8, 9)
	OpsetImport     []OperatorSetID     // Opset version(s)
	ProducerName    string              // Framework name (e.g., "pytorch", "tf")
	ProducerVersion string              // Framework version
	Domain          string              // Model domain
	ModelVersion    int64               // Model version number
	DocString       string              // Model description
	Graph           *GraphProto         // Computation graph
	MetadataProps   []StringStringEntry // Key-value metadata
}

ModelProto represents an ONNX model.

func Parse

func Parse(data []byte) (*ModelProto, error)

Parse parses an ONNX model from bytes.

func ParseFile

func ParseFile(path string) (*ModelProto, error)

ParseFile parses an ONNX model from file.

type NodeProto

type NodeProto struct {
	Name       string           // Node name (optional)
	OpType     string           // Operation type (e.g., "Conv", "MatMul", "Relu")
	Inputs     []string         // Input tensor names
	Outputs    []string         // Output tensor names
	Attributes []AttributeProto // Operation attributes
	Domain     string           // Custom domain (empty for default)
	DocString  string           // Node description
}

NodeProto represents a single operation.

type OperatorSetID

type OperatorSetID struct {
	Domain  string // Operator domain (empty for default)
	Version int64  // Opset version number
}

OperatorSetID identifies opset version.

type StringStringEntry

type StringStringEntry struct {
	Key   string
	Value string
}

StringStringEntry represents key-value metadata.

type TensorProto

type TensorProto struct {
	Name      string    // Tensor name
	DataType  int32     // Element data type
	Dims      []int64   // Tensor shape
	RawData   []byte    // Raw binary data (most common)
	FloatData []float32 // Float32 data (legacy)
	Int32Data []int32   // Int32 data (legacy)
	Int64Data []int64   // Int64 data (legacy)
	DocString string    // Tensor description
}

TensorProto represents a tensor (weights/initializers).

type TensorShapeProto

type TensorShapeProto struct {
	Dims []DimensionProto // Dimensions
}

TensorShapeProto describes tensor dimensions.

type TensorTypeProto

type TensorTypeProto struct {
	ElemType int32             // Element data type
	Shape    *TensorShapeProto // Tensor shape
}

TensorTypeProto describes tensor shape and element type.

type TypeProto

type TypeProto struct {
	TensorType *TensorTypeProto // Tensor type (most common)
}

TypeProto describes tensor type.

type ValueInfoProto

type ValueInfoProto struct {
	Name      string     // Tensor name
	Type      *TypeProto // Tensor type information
	DocString string     // Description
}

ValueInfoProto describes input/output tensor specifications.

Directories

Path Synopsis
Package operators implements ONNX operator mapping to Born tensor operations.
Package operators implements ONNX operator mapping to Born tensor operations.

Jump to

Keyboard shortcuts

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