backends

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 36 Imported by: 6 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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllInputTokens

func AllInputTokens(pipeline *BasePipeline) error

func CreateAudioTextTensors added in v0.8.2

func CreateAudioTextTensors(batch *PipelineBatch, model *Model, features [][][][]float32, isLonger []bool, inputs []TokenizedInput) error

CreateAudioTextTensors creates the feature, duration, and token tensors used by CLAP models.

func CreateImageTensors

func CreateImageTensors(batch *PipelineBatch, model *Model, preprocessed [][][][]float32) error

func CreateInputTensors

func CreateInputTensors(batch *PipelineBatch, model *Model) error

func CreateInputTensorsTraining

func CreateInputTensorsTraining(batch *PipelineBatch, model *Model) error

CreateInputTensorsTraining creates input tensors for training. Same as CreateInputTensors but we never pad the batch size as we expect regular batch sizes from the dataset.

func CreateMessages added in v0.6.0

func CreateMessages(batch *PipelineBatch, p *BasePipeline, inputs any, systemPrompt string) error

func CreateMessagesORT added in v0.6.0

func CreateMessagesORT(_ *PipelineBatch, _ any, _ string) error

func CreateModelBackend

func CreateModelBackend(ctx context.Context, model *Model, s *options.Options) error

func CreateTabularTensors added in v0.6.2

func CreateTabularTensors(batch *PipelineBatch, model *Model, features [][]float32) error

CreateTabularTensors builds input tensors for classic ML/tabular models.

func Decode

func Decode(tokens []uint32, tokenizer *Tokenizer) (string, error)

func DetectImageTensorFormat added in v0.6.0

func DetectImageTensorFormat(model *Model) (string, error)

DetectImageTensorFormat inspects the first image-like input and infers NHWC or NCHW.

func GetNames

func GetNames(info []InputOutputInfo) []string

func GetOnnxModelPath added in v0.6.2

func GetOnnxModelPath(ctx context.Context, model *Model) error

func HasDynamicMediaFeatures added in v0.9.0

func HasDynamicMediaFeatures(inputs []InputOutputInfo) bool

HasDynamicMediaFeatures reports whether a model has dynamic media feature inputs that can be supplied as empty tensors for text-only inference.

func LoadTokenizer

func LoadTokenizer(ctx context.Context, model *Model) error

func PreprocessImages added in v0.6.0

func PreprocessImages(format string, images []image.Image, preprocess []imageutil.PreprocessStep, normalize []imageutil.NormalizationStep) ([][][][]float32, error)

PreprocessImages converts the given images into a 4D tensor (batch × dim1 × dim2 × dim3) using the provided preprocess / normalization steps. The output is always 3 channels RGB — the alpha channel from image.Image.RGBA() is discarded. If your model expects a different channel count (e.g. 1-channel grayscale or 4-channel RGBA), build the tensor manually and create ORT tensors directly; do not rely on this helper.

func ReshapeOutput

func ReshapeOutput[T float32 | int64 | int32 | string](input []T, meta InputOutputInfo, batchSize int, paddingMask [][]bool) any

func RunGenerativeSessionOnBatch

func RunGenerativeSessionOnBatch(ctx context.Context, batch *PipelineBatch, p *BasePipeline, maxLength int, stopSequences []string, temperature *float64, topP *float64, seed *int, tools []string, guidance *Guidance) (chan SequenceDelta, chan error, error)

func RunPipeline added in v0.7.8

func RunPipeline[T any](ctx context.Context, size int, preprocess func(*PipelineBatch) error, forward func(context.Context, *PipelineBatch) error, postprocess func(*PipelineBatch) (*T, error)) (result *T, err error)

RunPipeline executes the common synchronous pipeline lifecycle. The typed postprocessor keeps the concrete output type visible to pipeline callers.

func RunSessionOnBatch

func RunSessionOnBatch(ctx context.Context, batch *PipelineBatch, p *BasePipeline) error

func RunStreamingASR added in v0.9.0

func RunStreamingASR(ctx context.Context, p *BasePipeline, chunks <-chan []float32, opts StreamingASROptions) (<-chan ASRResult, <-chan error, error)

RunStreamingASR transcribes PCM chunks, emitting copied incremental results. Closing chunks flushes buffered audio and finalizes word/segment timestamps.

func TokenizeInputPairs added in v0.7.0

func TokenizeInputPairs(batch *PipelineBatch, tk *Tokenizer, inputs [][2]string, sepToken string)

func TokenizeInputs

func TokenizeInputs(batch *PipelineBatch, tk *Tokenizer, inputs []string)

Types

type ASRResult added in v0.8.6

type ASRResult struct {
	Text     string
	Words    []ASRTimestamp
	Segments []ASRTimestamp
}

ASRResult is the transcription and timestamp output for one audio input.

func RunGenerativeASR added in v0.8.6

func RunGenerativeASR(ctx context.Context, p *BasePipeline, samples [][]float32, sampleRate int, prompt string) ([]ASRResult, error)

RunGenerativeASR transcribes audio through a GenAI session and returns copied text and timestamp results. The backend owns any native audio and generator resources for the duration of the call.

type ASRTimestamp added in v0.8.6

type ASRTimestamp struct {
	Text       string
	StartFrame int64
	StopFrame  int64
	StartTime  int64
	StopTime   int64
}

ASRTimestamp is a word or segment recognized by a generative ASR model. Times are int64 milliseconds; frames use the model's timestamp frame unit.

type Backend added in v0.7.8

type Backend interface {
	RunSessionOnBatch(context.Context, *PipelineBatch, *BasePipeline) error
	RunGenerativeSessionOnBatch(context.Context, *PipelineBatch, *BasePipeline, int, []string, *float64, *float64, *int, []string, *Guidance) (chan SequenceDelta, chan error, error)
	CreateMessages(*PipelineBatch, any, string) error
	CreateInputTensors(*PipelineBatch, *Model, bool) error
	CreateImageTensors(*PipelineBatch, *Model, [][][][]float32) error
	CreateImageTextTensors(*PipelineBatch, *Model, [][][][]float32, []TokenizedInput) error
	CreateAudioTensors(*PipelineBatch, *Model, [][]float32) error
	CreateTabularTensors(*PipelineBatch, *Model, [][]float32) error
}

Backend owns all operations that depend on the selected inference runtime. Pipelines use this contract instead of switching on a runtime name.

type BasePipeline

type BasePipeline struct {
	SessionContext   context.Context
	Model            *Model
	ONNXTimings      *timings
	TokenizerTimings *timings
	PipelineName     string
	Backend          Backend
	// EnableThinking selects the chat template behavior for generative pipelines.
	EnableThinking *bool
}

BasePipeline can be embedded by a pipeline.

func NewBasePipeline

func NewBasePipeline[T Pipeline](sessionContext context.Context, config PipelineConfig[T], model *Model) *BasePipeline

type ClassifierHeadChange added in v0.8.6

type ClassifierHeadChange struct {
	// Created is true when the model had no classification head and a new one was added on top of
	// its encoder output; false when an existing head was resized.
	Created bool
	// Kept lists the labels whose weights were carried over from the existing head.
	Kept []string
	// Added lists the labels that start from freshly initialised weights.
	Added []string
	// Removed lists the labels of the existing head that are not in the new label set.
	Removed []string
}

ClassifierHeadChange describes what SetClassifierLabels did to a model's graph.

func SetClassifierLabels added in v0.8.6

func SetClassifierLabels(model *protos.ModelProto, task ClassifierTask, oldLabels map[int]string, labels []string) (ClassifierHeadChange, error)

SetClassifierLabels rewrites a model's graph so that it classifies into exactly labels, in that order, and returns what it changed.

When the model already ends in a classification head (a MatMul and Add, or a Gemm, producing the first output), the head is resized: a label that is also in oldLabels keeps its trained weights, a new label gets freshly initialised ones, and an old label not in labels is dropped. oldLabels is the model's current id2label map; it may be empty, in which case every label starts fresh.

When the model has no head, which is the case for a plain encoder export whose output is the hidden states, a new linear head is added on top of them. For token classification it is applied to every token; for sequence classification the hidden states are first mean-pooled over the attention mask, as sentence-transformers does. The new head's output, named "logits", becomes the model's only output.

type ClassifierTask added in v0.8.6

type ClassifierTask int

ClassifierTask says what a classification head predicts: one label per text, or one per token.

const (
	// SequenceClassification heads output [batch, labels] logits.
	SequenceClassification ClassifierTask = iota
	// TokenClassification heads output [batch, sequence, labels] logits.
	TokenClassification
)

type ContentBlock added in v0.8.4

type ContentBlock struct {
	Type string `json:"type"` // text, image or audio
	Text string `json:"text,omitempty"`
	URL  string `json:"url,omitempty"`
}

ContentBlock is one ordered text or media item. URL is a local path or, for images, a data URI. Model-specific placeholders are supplied by the backend.

type DataType added in v0.8.6

type DataType string

DataType is the element type of a tensor input or output.

const (
	DataTypeUnknown DataType = ""
	DataTypeFloat32 DataType = "float32"
	DataTypeFloat64 DataType = "float64"
	DataTypeFloat16 DataType = "float16"
	DataTypeInt64   DataType = "int64"
	DataTypeInt32   DataType = "int32"
	DataTypeInt8    DataType = "int8"
	DataTypeUint8   DataType = "uint8"
	DataTypeBool    DataType = "bool"
	DataTypeString  DataType = "string"
)

type GenerationCompletion added in v0.9.0

type GenerationCompletion struct {
	TerminalTokenID        int32
	FinishReason           string
	MatchedStopStringIndex int32
	PromptTokens           uint64
	GeneratedTokens        uint64
	CachedPromptTokens     uint64
}

GenerationCompletion describes a completed engine turn. TerminalTokenID is the sampled EOS token, or -1; it must not be appended to generated text.

type GenerativeModel added in v0.7.1

type GenerativeModel interface {
	Generate(ctx context.Context, inputs [][]Message, tools []string, options *GenerativeOptions) (chan SequenceDelta, chan error, error)
	GetStatistics() PipelineStatistics
	Destroy() error
}

GenerativeModel abstracts either a generative session or engine.

type GenerativeOptions added in v0.7.1

type GenerativeOptions struct {
	Temperature *float64
	TopP        *float64
	Seed        *int
	Guidance    *Guidance
	MaxLength   int
}

GenerativeOptions contains settings for text generation.

type GoMLXModel

type GoMLXModel struct {
	Backend   compute.Backend
	OnnxModel onnx.Model
	Scope     *mlmodel.Scope
	Store     *mlmodel.Store
	Exec      *mlmodel.Exec
	Call      func(scope *mlmodel.Scope, inputs []*graph.Node) []*graph.Node

	DynamicAxes        [][]string
	DynamicAxesEnabled bool
	PaddingEnabled     bool
	BatchBuckets       []int // BatchBuckets defines bucket sizes for batch dimension padding.
	SequenceBuckets    []int // SequenceBuckets defines bucket sizes for sequence length padding.
	MaxCache           int   // MaxCache sets the maximum number of unique input shapes to cache.
	// contains filtered or unexported fields
}

func (*GoMLXModel) Close added in v0.7.8

func (m *GoMLXModel) Close()

func (*GoMLXModel) ResetExec added in v0.8.4

func (m *GoMLXModel) ResetExec() error

ResetExec rebuilds the inference executor, dropping its cached graphs. On a backend that embeds variables as constants (the Go backend), each cached graph holds the weights it was built with, so after training changes the weights, inference only sees them once the executor is reset.

func (*GoMLXModel) Save

func (m *GoMLXModel) Save(w io.Writer) error

type GoTokenizer

type GoTokenizer struct {
	Tokenizer     *hftokenizer.Tokenizer
	TypeIDs       bool
	AttentionMask bool
}

type GraphTransform added in v0.8.6

type GraphTransform func(model *Model, graph *protos.ModelProto) error

GraphTransform rewrites a model's ONNX graph after its config is read and before the graph is built. It may also update the model, e.g. its IDLabelMap to match a resized classifier head.

type Guidance added in v0.7.0

type Guidance struct {
	Type           GuidanceType
	Data           string
	EnableFFTokens bool
}

Guidance configures constrained (guided) generation. EnableFFTokens speeds up generation by force-forwarding tokens that satisfy the grammar without calling the model. Requires BatchSize=1.

type GuidanceType added in v0.7.0

type GuidanceType string

GuidanceType specifies the constrained-generation strategy.

const (
	GuidanceTypeJSONSchema  GuidanceType = "json_schema"
	GuidanceTypeRegex       GuidanceType = "regex"
	GuidanceTypeLarkGrammar GuidanceType = "lark_grammar"
)

type ImageTextInput added in v0.8.1

type ImageTextInput struct {
	Image     image.Image
	ImagePath string
	Text      string
}

ImageTextInput is one paired image and text example for multimodal models. The image is kept as an image.Image so callers can use in-memory images without coupling the public contract to a particular image decoder.

func (ImageTextInput) Validate added in v0.8.1

func (i ImageTextInput) Validate() error

Validate checks the common requirements shared by image/text pipelines.

type InputOutputInfo

type InputOutputInfo struct {
	// The name of the input or output
	Name string
	// The input or output's dimensions, if it's a tensor. This should be
	// ignored for non-tensor types.
	Dimensions Shape
	// The element type of the tensor. DataTypeUnknown when the backend does not
	// report it or the type has no Go representation in hugot.
	DataType DataType
}

type Message added in v0.6.0

type Message struct {
	Role      string   `json:"role"`
	Content   string   `json:"content"`
	ImageURLs []string `json:"image_urls,omitempty"` // File paths or data URIs for multimodal support
	AudioURLs []string `json:"audio_urls,omitempty"` // File paths for multimodal support
	// ContentBlocks preserves text/image/audio interleaving. It is mutually
	// exclusive with Content, ImageURLs and AudioURLs.
	ContentBlocks []ContentBlock `json:"content_blocks,omitempty"`
	// contains filtered or unexported fields
}

Message represents a single message in a conversation. Images and audio can be included via ImageURLs and AudioURLs for multimodal models.

type Model

type Model struct {
	Backend    Backend
	OnnxReader io.ReadCloser
	IDLabelMap map[int]string
	ORTModel   *ORTModel
	GoMLXModel *GoMLXModel
	Tokenizer  *Tokenizer
	Pipelines  map[string]Pipeline

	ID                    string
	Path                  string
	OnnxFilename          string
	OnnxPath              string
	UnknownToken          string
	SeparatorToken        string
	InputsMeta            []InputOutputInfo
	OutputsMeta           []InputOutputInfo
	MaxPositionEmbeddings int
	ContextLength         int
	ImageSize             int

	IsGenerative bool
	// contains filtered or unexported fields
}

func LoadModel

func LoadModel(ctx context.Context, path string, onnxFilename string, opts *options.Options, isGenerative bool) (*Model, error)

func LoadModelWithGraphTransform added in v0.8.6

func LoadModelWithGraphTransform(ctx context.Context, path string, onnxFilename string, opts *options.Options, transform GraphTransform) (*Model, error)

LoadModelWithGraphTransform loads a non-generative model like LoadModel, rewriting its ONNX graph with transform before it is built. Only the GoMLX backends (Go, XLA, and ORT with WithGoMLX) support it, as the native ORT backend hands the file to the runtime unparsed.

func (*Model) Close added in v0.7.8

func (model *Model) Close() error

Close releases all resources owned by the model. It is safe to call more than once, which makes session and pipeline cleanup composable.

func (*Model) LoadGraph added in v0.8.2

func (model *Model) LoadGraph(ctx context.Context, filename string) (*Model, error)

LoadGraph loads and caches an additional ONNX graph relative to the model directory, using the parent's backend settings and no tokenizer. The parent owns the returned model and closes it when the parent is closed.

func (*Model) RunTensors added in v0.8.2

func (model *Model) RunTensors(ctx context.Context, inputs map[string]Tensor) (map[string]Tensor, error)

RunTensors executes named inputs without pipeline padding or reshaping. Returned shapes and data are copies owned by the caller. Inputs must not be modified until the call returns. Close waits for active calls to finish.

func (*Model) UsesStreamingASR added in v0.9.0

func (model *Model) UsesStreamingASR() bool

UsesStreamingASR reports whether the model was loaded as a streaming speech package.

func (*Model) ValidateMultimodalSession added in v0.8.4

func (model *Model) ValidateMultimodalSession() error

ValidateMultimodalSession rejects engine scheduling before loading media. Audio and any-to-any generation require a session; vision turns can use an engine.

type ModelLoading added in v0.8.2

type ModelLoading string

ModelLoading selects the model runtime independently of generation behavior.

const (
	ModelLoadingDefault ModelLoading = ""
	ModelLoadingONNX    ModelLoading = "onnx"
	ModelLoadingGenAI   ModelLoading = "genai"
)

type ORTModel

type ORTModel struct {
	Generative *generativeORTAdapter
}

func (*ORTModel) Close added in v0.7.8

func (m *ORTModel) Close() error

type OutputInfo

type OutputInfo struct {
	Name       string
	Dimensions []int64
}

type Pipeline

type Pipeline interface {
	GetStatistics() PipelineStatistics                          // Get the pipeline running statistics
	Validate() error                                            // Validate the pipeline for correctness
	GetMetadata() PipelineMetadata                              // Return metadata information for the pipeline
	GetModel() *Model                                           // Return the model used by the pipeline
	IsGenerative() bool                                         // Return whether the pipeline is generative
	Run(context.Context, []string) (PipelineBatchOutput, error) // Run the pipeline on an input
}

Pipeline is the interface that any pipeline must implement.

type PipelineBatch

type PipelineBatch struct {
	InputValues any
	// InputMetadata holds pipeline-specific input information that must survive
	// tensor creation until postprocessing.
	InputMetadata any
	// Multimodal support
	// Images holds the aggregated *ortgenai.Images for the batch when the
	// backend loads them (e.g. generative ORT session).
	Images any
	// Audios is the audio counterpart of Images; set by the backend when a
	// conversation (or conversations) carries AudioURLs.
	Audios             any
	MultimodalMessages [][]Message
	ImageText          []ImageTextInput
	ImageValues        [][][][]float32
	AudioFeatures      [][][][]float32
	AudioIsLonger      []bool
	// SynthesizeEmptyMediaFeatures enables empty image/video/audio feature
	// tensors for text-only pipeline calls that use models with those inputs.
	SynthesizeEmptyMediaFeatures bool
	DestroyInputs                func() error
	DestroyMultimodal            func() error
	Input                        []TokenizedInput
	PaddingMask                  [][]bool
	OutputValues                 []any
	Size                         int
	MaxSequenceLength            int
	MaxNewTokens                 int
	// PaddedBatchSize is the bucketed batch size used when the batch dimension is padded.
	// Zero means no batch padding was applied.
	PaddedBatchSize int
	QueryCount      int
}

PipelineBatch represents a batch of inputs that runs through the pipeline.

func NewBatch

func NewBatch(size int) *PipelineBatch

NewBatch initializes a new batch for inference.

func (*PipelineBatch) Destroy

func (b *PipelineBatch) Destroy() error

type PipelineBatchOutput

type PipelineBatchOutput interface {
	GetOutput() []any
}

type PipelineConfig

type PipelineConfig[T Pipeline] struct {
	ModelPath    string
	Name         string
	OnnxFilename string
	ModelLoading ModelLoading
	Options      []PipelineOption[T]
}

PipelineConfig is a configuration for a pipeline type that can be used to create that pipeline.

type PipelineMetadata

type PipelineMetadata struct {
	OutputsInfo []OutputInfo
}

type PipelineOption

type PipelineOption[T Pipeline] func(eo T) error

PipelineOption is an option for a pipeline type.

type PipelineStatistics

type PipelineStatistics struct {
	TokenizerTotalTime             time.Duration
	TokenizerExecutionCount        uint64
	TokenizerAvgQueryTime          time.Duration
	OnnxTotalTime                  time.Duration
	OnnxExecutionCount             uint64
	OnnxAvgQueryTime               time.Duration
	TotalQueries                   uint64
	TotalDocuments                 uint64
	AverageLatency                 time.Duration
	AverageBatchSize               float64
	FilteredResults                uint64
	AvgPrefillSeconds              float64
	TokensPerSecond                float64
	CumulativePrefillSum           float64
	CumulativePrefillCount         int
	CumulativeTokens               int
	CumulativeTokenDurationSeconds float64
}

func (*PipelineStatistics) ComputeOnnxStatistics

func (p *PipelineStatistics) ComputeOnnxStatistics(timings *timings)

func (*PipelineStatistics) ComputeTokenizerStatistics

func (p *PipelineStatistics) ComputeTokenizerStatistics(timings *timings)

func (*PipelineStatistics) Print

func (p *PipelineStatistics) Print()

type SequenceDelta added in v0.6.0

type SequenceDelta struct {
	Token    string
	Sequence int
	// Completion is emitted by engine mode when a turn ends. Token is empty.
	Completion *GenerationCompletion
}

type Shape

type Shape []int64

func NewShape

func NewShape(dimensions ...int64) Shape

NewShape Returns a Shape, with the given dimensions.

func (Shape) String

func (s Shape) String() string

func (Shape) ValuesInt

func (s Shape) ValuesInt() []int

type StreamingASROptions added in v0.9.0

type StreamingASROptions struct {
	ChunkSamples int
	// ProcessorOptions supports use_vad, vad_threshold, silence_duration_ms,
	// and prefix_padding_ms. The runtime validates values and model support.
	ProcessorOptions map[string]string
	// RuntimeOptions configures generator settings such as lang_id.
	RuntimeOptions map[string]string
}

StreamingASROptions configures a streaming speech package. ChunkSamples must match the package's maximum PCM chunk size at the pipeline sample rate.

type Tensor added in v0.8.2

type Tensor struct {
	Shape []int64
	Data  any
}

Tensor holds a runtime shape and flat []float32, []int32, []int64, []bool, or []string data. String tensors are supported by the ORT backend only. An empty shape denotes a scalar with one element.

type TokenizedInput

type TokenizedInput struct {
	Raw               string
	Tokens            []string
	TokenIDs          []uint32
	TypeIDs           []uint32
	AttentionMask     []uint32
	SpecialTokensMask []uint32
	Offsets           [][2]uint
	MaxAttentionIndex int
}

TokenizedInput holds the result of running tokenizer on an input.

type Tokenizer

type Tokenizer struct {
	GoTokenizer *GoTokenizer

	MaxAllowedTokens int
	// contains filtered or unexported fields
}

func (*Tokenizer) Close added in v0.7.8

func (t *Tokenizer) Close() error

type VariablePlacement added in v0.8.6

type VariablePlacement struct {
	Layers     map[string]int  // transformer layer index of each weight
	Embeddings map[string]bool // weights of the embeddings block
}

VariablePlacement says where in the transformer each weight of an ONNX graph sits. Keys are GoMLX variable names, i.e. ONNX initializer names with "/" replaced by "|".

Exporters name many weights anonymously: PyTorch stores a transposed linear weight as "onnx::MatMul_977", which says nothing about its layer. The node that consumes it does ("/encoder/layer.0/attention/self/query/MatMul"), so the placement is read from the consumers.

func PlaceVariables added in v0.8.6

func PlaceVariables(graph *protos.GraphProto) VariablePlacement

PlaceVariables reads the layer and embeddings placement of every initializer from the nodes that consume it. A weight used in more than one layer (tied weights) gets no layer. It also places the fused QKV weights onnx-gomlx creates at load time ("__fused_wQKV_<input>"), which are not in the graph yet, by the layer of the projections that read <input>.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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