tract

package module
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0, MIT Imports: 6 Imported by: 0 modules, 0 packages

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

tract-go

Go Reference CI Release

Go bindings for tract, Sonos' self-contained neural network inference engine: run ONNX and NNEF models in-process, on the CPU, from Go.

go get go.riptides.io/tract

The module ships tract's C API as prebuilt static libraries, so programs link it in: no shared library to install or load at run time, and no Rust toolchain to build. That also means a binary signed with Apple's hardened runtime has no third-party library for library validation to reject.

Platform Library
linux/amd64 lib/linux_amd64/libtract.a
linux/arm64 lib/linux_arm64/libtract.a
darwin/arm64 lib/darwin_arm64/libtract.a
windows/amd64 lib/windows_amd64/libtract.a

Building needs cgo and a C toolchain: on macOS the Xcode command line tools, on Windows a MinGW-w64 gcc on the PATH (from MSYS2 or llvm-mingw, as for any cgo package there; the Windows library is built for Rust's GNU target to link with it). On other platforms, or with CGO_ENABLED=0, the package compiles against a stub whose every call returns tract.ErrUnsupported, so code using it still builds everywhere.

Use

onnx, err := tract.NewOnnx()
if err != nil {
	return err
}
defer onnx.Close()

im, err := onnx.Load("model.onnx")
if err != nil {
	return err
}
// Optional: pin input types and shapes; letters are symbolic dimensions.
if err := im.SetInputFactSpec(0, "1,S,i64"); err != nil {
	return err
}
m, err := im.IntoModel() // consumes im
if err != nil {
	return err
}
r, err := m.IntoRunnable() // consumes m
if err != nil {
	return err
}
defer r.Close()

ids, err := tract.NewTensor([]int{1, 4}, []int64{101, 2023, 2003, 102})
if err != nil {
	return err
}
defer ids.Close()
out, err := r.Run(ids)
if err != nil {
	return err
}
defer out[0].Close()
logits, err := tract.TensorData[float32](out[0])
  • Every object holds memory owned by tract: Close it. A dropped object is released by a cleanup eventually, but at no predictable time.
  • IntoModel, IntoRunnable and Runtime.Prepare consume their model, even when they fail.
  • Runnable.Run is safe for concurrent use: each run gets a state of its own. Nothing else may be used concurrently with its Close.
  • Tensors copy their data in and out; NewTensorFromBytes takes raw data for types without a Go equivalent, such as tract.F16.
  • tract's C API does not catch Rust panics: one aborts the process.

The API follows tract's C API (tract.h); see the package documentation for the rest.

Versions

A release is numbered after the tract line it carries: v0.23.N links tract 0.23.x, v0.24.N tract 0.24.x, and the patch number is this module's own. build.env pins the exact tract commit, the Rust toolchain and the cbindgen that generates tract.h; a release names its tract version in its notes, and tract.Version() reports it at run time. See RELEASING.md.

The library adds about 17 MB to a stripped binary. go get downloads every platform's library in one module zip: they are 26 MB (darwin/arm64) and 46 MB (linux/arm64) uncompressed, and the zip with those two is 20 MB.

Building the libraries

The prebuilt libraries live only in release commits; main does not carry them. To work on the binding from main, either fetch a release's library for your host:

scripts/fetch-libs.sh v0.1.0

or build it, which takes rustup and a few minutes:

rustup toolchain install "$(sed -n 's/^RUST_TOOLCHAIN=//p' build.env)" -c llvm-tools
scripts/build-lib.sh
go test -race ./...

scripts/build-lib.sh --header also regenerates tract.h (needs cargo install cbindgen at the pinned version). See RELEASING.md for how a version is cut.

License

The Go code is licensed under either of Apache License 2.0 or MIT, at your option, as tract itself is. The prebuilt libraries contain tract and the Rust crates it depends on, all under permissive licenses; each release lists them in lib/THIRD-PARTY-NOTICES.txt.

Documentation

Overview

Package tract runs ONNX and NNEF neural networks in-process with Sonos' tract (https://github.com/sonos/tract), a self-contained CPU inference engine written in Rust.

The tract C API is linked statically from the prebuilt libraries this module ships for linux/amd64, linux/arm64, darwin/arm64 and windows/amd64 (built for MinGW, which cgo uses there), so a program using it needs no shared library at run time and no Rust toolchain to build. Other platforms, and builds with cgo disabled, compile against a stub whose every call returns ErrUnsupported.

A model goes through the same stages as in tract's other APIs:

onnx, _ := tract.NewOnnx()
defer onnx.Close()
im, _ := onnx.Load("model.onnx")            // *InferenceModel
_ = im.SetInputFactSpec(0, "1,S,i64")       // optional: types and shapes
m, _ := im.IntoModel()                      // *Model (consumes im)
r, _ := m.IntoRunnable()                    // *Runnable (consumes m)
defer r.Close()
out, _ := r.Run(input)                      // []*Tensor

Every object holds memory owned by tract: Close it when done. A finalizer releases objects that are dropped without Close, but at an unpredictable time. Methods whose name starts with Into, and Runtime.Prepare, consume their receiver or argument whether they succeed or not.

A Runnable may be run from several goroutines at once: every Run uses a state of its own. Other objects must not be used concurrently with their Close.

A Rust panic inside tract aborts the process: the C API does not turn panics into errors.

Example
package main

import (
	"fmt"
	"log"

	"go.riptides.io/tract"
)

func main() {
	onnx, err := tract.NewOnnx()
	if err != nil {
		log.Fatal(err)
	}
	defer onnx.Close()

	im, err := onnx.Load("testdata/linear.onnx")
	if err != nil {
		log.Fatal(err)
	}
	// Optional: pin the input's type and shape ("N" stays symbolic otherwise).
	if err := im.SetInputFactSpec(0, "1,3,f32"); err != nil {
		log.Fatal(err)
	}
	m, err := im.IntoModel()
	if err != nil {
		log.Fatal(err)
	}
	r, err := m.IntoRunnable()
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	x, err := tract.NewTensor([]int{1, 3}, []float32{1, 1, 1})
	if err != nil {
		log.Fatal(err)
	}
	defer x.Close()
	out, err := r.Run(x)
	if err != nil {
		log.Fatal(err)
	}
	defer out[0].Close()
	y, err := tract.TensorData[float32](out[0])
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(y)
}
Output:
[9.5 11.5]

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("tract: object is closed or consumed")

ErrClosed is returned when an object is used after Close, or after a call that consumed it.

View Source
var ErrUnsupported = errors.New("tract: unsupported platform or cgo disabled")

ErrUnsupported is returned by every call on a platform without a prebuilt tract library, or when cgo is disabled.

Functions

func TensorData

func TensorData[T Element](t *Tensor) ([]T, error)

TensorData is a copy of t's elements, which must be of type T.

func Version

func Version() string

Version is the version of the linked tract library, or "" when unsupported.

Types

type DatumType

type DatumType int

DatumType is the element type of a tensor.

const (
	Bool       DatumType = 1
	U8         DatumType = 17
	U16        DatumType = 18
	U32        DatumType = 20
	U64        DatumType = 24
	I8         DatumType = 33
	I16        DatumType = 34
	I32        DatumType = 36
	I64        DatumType = 40
	F16        DatumType = 50
	F32        DatumType = 52
	F64        DatumType = 56
	ComplexI16 DatumType = 66
	ComplexI32 DatumType = 68
	ComplexI64 DatumType = 72
	ComplexF16 DatumType = 82
	ComplexF32 DatumType = 84
	ComplexF64 DatumType = 88
)

The datum types of tract's C API.

func DatumTypeOf

func DatumTypeOf[T Element]() DatumType

DatumTypeOf is the datum type of T.

func (DatumType) Size

func (d DatumType) Size() int

Size is the size of one element in bytes, or 0 for an unknown type.

func (DatumType) String

func (d DatumType) String() string

type Dim

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

Dim is a tensor dimension: a number or an expression over symbols.

func (*Dim) Close

func (d *Dim) Close() error

Close releases the dimension.

func (*Dim) Int64

func (d *Dim) Int64() (int64, error)

Int64 is the dimension's value; it fails for a symbolic dimension.

func (*Dim) String

func (d *Dim) String() string

String is the dimension, such as "3" or "S".

type Element

type Element interface {
	bool | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | float32 | float64
}

Element is a Go type with a tract datum type of the same memory layout.

type Error

type Error struct {
	// Op is the tract C function that failed.
	Op string
	// Msg is tract's description of the error.
	Msg string
}

Error is an error reported by tract.

func (*Error) Error

func (e *Error) Error() string

type Fact

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

Fact is the type and shape of a typed model's input or output.

func (*Fact) Close

func (f *Fact) Close() error

Close releases the fact.

func (*Fact) DatumType

func (f *Fact) DatumType() (DatumType, error)

DatumType is the element type.

func (*Fact) Dim

func (f *Fact) Dim(axis int) (*Dim, error)

Dim is the dimension along axis, concrete or symbolic.

func (*Fact) Rank

func (f *Fact) Rank() (int, error)

Rank is the number of dimensions.

func (*Fact) String

func (f *Fact) String() string

String is the fact as a spec, such as "1,S,i64".

type InferenceFact

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

InferenceFact is what is known of an InferenceModel input's or output's type and shape.

func (*InferenceFact) Close

func (f *InferenceFact) Close() error

Close releases the fact.

func (*InferenceFact) String

func (f *InferenceFact) String() string

String is the fact as a spec.

type InferenceModel

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

InferenceModel is a loaded ONNX model whose types and shapes may still be partly unknown. Set its input facts if needed, then call IntoModel.

func (*InferenceModel) Analyse

func (m *InferenceModel) Analyse() error

Analyse runs type and shape inference on the model.

func (*InferenceModel) Close

func (m *InferenceModel) Close() error

Close releases the model.

func (*InferenceModel) InputCount

func (m *InferenceModel) InputCount() (int, error)

InputCount is the number of inputs.

func (*InferenceModel) InputFact

func (m *InferenceModel) InputFact(i int) (*InferenceFact, error)

InputFact is what is known of input i's type and shape.

func (*InferenceModel) InputName

func (m *InferenceModel) InputName(i int) (string, error)

InputName is the name of input i.

func (*InferenceModel) IntoModel

func (m *InferenceModel) IntoModel() (*Model, error)

IntoModel turns the model into a typed Model. It consumes m, even on error.

func (*InferenceModel) OutputCount

func (m *InferenceModel) OutputCount() (int, error)

OutputCount is the number of outputs.

func (*InferenceModel) OutputFact

func (m *InferenceModel) OutputFact(i int) (*InferenceFact, error)

OutputFact is what is known of output i's type and shape.

func (*InferenceModel) OutputName

func (m *InferenceModel) OutputName(i int) (string, error)

OutputName is the name of output i.

func (*InferenceModel) ParseFact

func (m *InferenceModel) ParseFact(spec string) (*InferenceFact, error)

ParseFact parses a fact spec in the context of this model.

func (*InferenceModel) SetInputFact

func (m *InferenceModel) SetInputFact(i int, f *InferenceFact) error

SetInputFact sets input i's type and shape. f stays owned by the caller.

func (*InferenceModel) SetInputFactSpec

func (m *InferenceModel) SetInputFactSpec(i int, spec string) error

SetInputFactSpec sets input i's type and shape from a spec such as "1,S,i64" or "B,224,224,3,f32" (letters are symbolic dimensions).

func (*InferenceModel) SetOutputFact

func (m *InferenceModel) SetOutputFact(i int, f *InferenceFact) error

SetOutputFact sets output i's type and shape. f stays owned by the caller.

func (*InferenceModel) SetOutputFactSpec

func (m *InferenceModel) SetOutputFactSpec(i int, spec string) error

SetOutputFactSpec sets output i's type and shape from a spec.

type Model

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

Model is a typed model, ready to be transformed and made runnable.

func (*Model) Close

func (m *Model) Close() error

Close releases the model.

func (*Model) InputCount

func (m *Model) InputCount() (int, error)

InputCount is the number of inputs.

func (*Model) InputFact

func (m *Model) InputFact(i int) (*Fact, error)

InputFact is input i's type and shape.

func (*Model) InputName

func (m *Model) InputName(i int) (string, error)

InputName is the name of input i.

func (*Model) IntoRunnable

func (m *Model) IntoRunnable() (*Runnable, error)

IntoRunnable optimises the model for the default CPU runtime. It consumes m, even on error.

func (*Model) OutputCount

func (m *Model) OutputCount() (int, error)

OutputCount is the number of outputs.

func (*Model) OutputFact

func (m *Model) OutputFact(i int) (*Fact, error)

OutputFact is output i's type and shape.

func (*Model) OutputName

func (m *Model) OutputName(i int) (string, error)

OutputName is the name of output i.

func (*Model) ParseFact

func (m *Model) ParseFact(spec string) (*Fact, error)

ParseFact parses a fact spec in the context of this model.

func (*Model) Transform

func (m *Model) Transform(spec string) error

Transform applies a named transform, such as "f32_to_f16", or a JSON object with a "name" key and its parameters.

type Nnef

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

Nnef loads NNEF models.

func NewNnef

func NewNnef() (*Nnef, error)

NewNnef creates an NNEF loader.

func (*Nnef) Close

func (n *Nnef) Close() error

Close releases the loader. Models it loaded are unaffected.

func (*Nnef) Load

func (n *Nnef) Load(path string) (*Model, error)

Load reads the NNEF model at path: a directory, or a .tar or .tar.gz archive.

type Onnx

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

Onnx loads ONNX models.

func NewOnnx

func NewOnnx() (*Onnx, error)

NewOnnx creates an ONNX loader.

func (*Onnx) Close

func (o *Onnx) Close() error

Close releases the loader. Models it loaded are unaffected.

func (*Onnx) Load

func (o *Onnx) Load(path string) (*InferenceModel, error)

Load parses the .onnx file at path.

func (*Onnx) LoadBuffer

func (o *Onnx) LoadBuffer(data []byte) (*InferenceModel, error)

LoadBuffer parses an ONNX model held in memory.

type Runnable

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

Runnable is a model ready to run. Run is safe for concurrent use.

func (*Runnable) Close

func (r *Runnable) Close() error

Close releases the runnable. States spawned from it stay valid.

func (*Runnable) InputCount

func (r *Runnable) InputCount() (int, error)

InputCount is the number of inputs.

func (*Runnable) InputFact

func (r *Runnable) InputFact(i int) (*Fact, error)

InputFact is input i's type and shape.

func (*Runnable) OutputCount

func (r *Runnable) OutputCount() (int, error)

OutputCount is the number of outputs.

func (*Runnable) OutputFact

func (r *Runnable) OutputFact(i int) (*Fact, error)

OutputFact is output i's type and shape.

func (*Runnable) Run

func (r *Runnable) Run(inputs ...*Tensor) ([]*Tensor, error)

Run runs the model on one tensor per input, in order, and returns one tensor per output. The inputs stay owned by the caller; the caller owns and must Close the outputs.

func (*Runnable) SpawnState

func (r *Runnable) SpawnState() (*State, error)

SpawnState creates a state for running a stateful model step by step.

type Runtime

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

Runtime prepares models for a backend.

func RuntimeForName

func RuntimeForName(name string) (*Runtime, error)

RuntimeForName returns a runtime by name. "default" is the CPU runtime, which names itself "cpu".

func (*Runtime) Close

func (r *Runtime) Close() error

Close releases the runtime.

func (*Runtime) Name

func (r *Runtime) Name() (string, error)

Name is the runtime's name.

func (*Runtime) Prepare

func (r *Runtime) Prepare(m *Model) (*Runnable, error)

Prepare makes m runnable on this runtime. It consumes m, even on error.

type State

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

State runs a stateful model step by step. It is not safe for concurrent use.

func (*State) Close

func (s *State) Close() error

Close releases the state.

func (*State) Run

func (s *State) Run(inputs ...*Tensor) ([]*Tensor, error)

Run runs one step, like Runnable.Run.

type Tensor

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

Tensor is an n-dimensional array owned by tract.

func NewTensor

func NewTensor[T Element](shape []int, data []T) (*Tensor, error)

NewTensor copies data, laid out in row-major order, into a tensor of shape.

func NewTensorFromBytes

func NewTensorFromBytes(dt DatumType, shape []int, data []byte) (*Tensor, error)

NewTensorFromBytes copies raw little-endian element data into a tensor, for datum types without a Go equivalent such as F16.

func (*Tensor) Bytes

func (t *Tensor) Bytes() ([]byte, error)

Bytes is a copy of the tensor's raw element data.

func (*Tensor) Clone

func (t *Tensor) Clone() (*Tensor, error)

Clone returns an independent copy of t.

func (*Tensor) Close

func (t *Tensor) Close() error

Close releases the tensor.

func (*Tensor) ConvertTo

func (t *Tensor) ConvertTo(dt DatumType) (*Tensor, error)

ConvertTo returns a copy of t converted to dt.

func (*Tensor) DatumType

func (t *Tensor) DatumType() (DatumType, error)

DatumType is the element type.

func (*Tensor) Shape

func (t *Tensor) Shape() ([]int, error)

Shape is the tensor's shape.

func (*Tensor) String

func (t *Tensor) String() string

String is tract's debug rendering of the tensor.

Directories

Path Synopsis
lib
darwin_arm64
Package darwin_arm64 holds the prebuilt static tract library for darwin/arm64.
Package darwin_arm64 holds the prebuilt static tract library for darwin/arm64.
linux_amd64
Package linux_amd64 holds the prebuilt static tract library for linux/amd64.
Package linux_amd64 holds the prebuilt static tract library for linux/amd64.
linux_arm64
Package linux_arm64 holds the prebuilt static tract library for linux/arm64.
Package linux_arm64 holds the prebuilt static tract library for linux/arm64.
windows_amd64
Package windows_amd64 holds the prebuilt static tract library for windows/amd64.
Package windows_amd64 holds the prebuilt static tract library for windows/amd64.

Jump to

Keyboard shortcuts

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