hugot

package module
v0.8.5 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 33 Imported by: 51 modules, 11 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 ¶

Hugot: ONNX Transformer Pipelines for Go

Go Reference Go Report Card Coverage Status

Go Gopher Transformer

What

TL;DR: Hugot brings Hugging Face-style transformer pipelines to Go, letting you run and fine-tune ONNX models for text, vision, audio, and multimodal workloads directly inside your Go applications, with pluggable pure Go, ONNX Runtime, and OpenXLA backends.

The goal of this library is to provide an easy, scalable, and hassle-free way to run transformer pipelines inference and training in golang applications, such as Hugging Face 🤗 transformers pipelines. It is built on the following principles:

  1. Hugging Face compatibility: models trained and tested using the python Hugging Face transformer library can be exported to onnx and used with the Hugot pipelines to obtain identical predictions as in the python version.
  2. Hassle-free and performant production use: we exclusively support onnx models. Pytorch transformer models that don't have an onnx version can be easily exported to onnx via Hugging Face Optimum, and used with the library.
  3. Run on your hardware: this library is for those who want to run transformer models tightly coupled with their go applications, without the performance drawbacks of having to hit a rest API or the hassle of setting up and maintaining e.g. a python RPC service that talks to go.
  4. Simplicity: the Hugot API allows you to easily deploy pipelines without having to write your own inference or training code. It also now includes a pure Go backend for minimal dependencies!

We support inference on CPU and on all accelerators supported by ONNX Runtime/OpenXLA. Note, however, that currently only CPU, TPU, and GPU inference on Nvidia GPUs via CUDA, are tested (see below).

IMPORTANT: The Go backend is designed for simpler workloads, environments that disallow cgo, and for smaller models such as all-MiniLM-L6-v2. It works best with small batches of roughly 32 inputs per call. If you have performance requirements, please move to a C backend such as XLA or ORT (detailed below).

Hugot loads and saves models in the ONNX format.

Why

Developing and fine-tuning transformer models with the Hugging Face python library is great, but if your production stack is golang-based being able to reliably deploy and scale the resulting pytorch models can be challenging. This library aims to allow you to just lift-and-shift your python model and use the same Hugging Face pipelines you use for development for inference in a go application.

For whom

For the golang developer or ML engineer who wants to run or fine-tune transformer pipelines on their own hardware and tightly coupled with their own application, without having to deal with writing their own inference or training code.

By whom

Hugot is brought to you by the friendly folks at Knights Analytics, who use Hugot in production to automate ai-powered data curation.

Implemented pipelines

Currently, we have implementations for the following transformer pipelines:

Note: Some backends have incompatibilities with some pipeline/model combinations. Please report (or fix such issues with a PR), ideally on the repo of the backend in question (e.g. GoMLX or Onnx Runtime).

Installation and usage

Choosing a backend

Hugot supports pluggable backends to perform the tokenization and run the ONNX models. Currently, we support the following backends:

The native Go backend is always available, as it does not require any cgo dependencies. It is provided by the GoMLX project. Note: currently, enabling GOEXPERIMENT=simd gives this backend a significant performance boost.

Onnx Runtime can be included at compile time via the build tag "-tags ORT". It is currently the fastest backend for inference and supports all pipelines, including generative pipelines such as text generation.

OpenXLA can be included at compile time via the build tag "-tags XLA". This is the only backend that supports TPUs. Note that it does not yet support generative pipelines or dynamic shapes.

CUDA requires a C backend, either OpenXLA or Onnx Runtime.

Once compiled, Hugot can be instantiated with your backend of choice via calling NewGoSession(), NewXLASession() or NewORTSession() respectively.

You may combine build tags "-tags XLA,ORT" or use "-tags ALL" to be able to use all available backends interchangeably.

Usage

To use Hugot as a library in your application, you can directly import it and follow the example below.

Backends
  • if using Onnx Runtime, the libonnxruntime.so file should be obtained from the releases section of this page. If you want to use other architectures than linux/amd64 you will have to download it from the ONNX Runtime releases page, see the dockerfile as an example. Hugot looks for this file at /usr/lib/libonnxruntime.so by default. A different location can be specified by passing the WithOnnxLibraryPath() option to NewORTSession(), e.g:
session, err := NewORTSession(
    ctx,
    options.WithOnnxLibraryPath("/path/to/my/lib/directory"),
)
  • if using XLA, the easiest way is to run "GOPROXY=direct go run github.com/gomlx/go-xla/cmd/pjrt_installer@latest -plugin=linux -version=v${GOPJRT_VERSION} -path=/usr/local/lib/go-xla", which will install the XLA backend provided by the goMLX project.

Alternatively, you can also use the docker image which has all the above dependencies already baked in.

  • the latest versions of the onnxruntime and gopjrt libraries that are used in our testing can be found in the bakefile.

The library can be used as follows:

package main

import (
    "github.com/knights-analytics/hugot"
    "context"
	"encoding/json"
    "fmt"
)

func check(err error) {
    if err != nil {
        panic(err.Error())
    }
}

func main() {
    // all sessions require context.Context
    ctx := context.Background()
    // start a new session
    session, err := hugot.NewGoSession(ctx)
	// For XLA (requires go build tags "XLA" or "ALL"):
	// session, err := hugot.NewXLASession(ctx)
	// For ORT (requires go build tags "ORT" or "ALL"):
	// session, err := hugot.NewORTSession(ctx)
	// This looks for the libonnxruntime.so library in its default path, e.g. /usr/lib
    // If your libonnxruntime.so is somewhere else, you can explicitly set it by using WithOnnxLibraryPath
    // session, err := hugot.NewORTSession(ctx, WithOnnxLibraryPath("/path/to/my/lib/directory"))
	check(err)
	
    // A successfully created hugot session needs to be destroyed when you're done
    defer func (session *hugot.Session) {
    err = session.Destroy()
    check(err)
    }(session)

    // Let's download an onnx sentiment test classification model in the current directory
    // note: if you compile your library with build flag NODOWNLOAD, this will exclude the downloader.
    // Useful in case you just want the core engine (because you already have the models)
    modelPath, err := hugot.DownloadModel("KnightsAnalytics/distilbert-base-uncased-finetuned-sst-2-english", "./models/", hugot.NewDownloadOptions())
    check(err)

    // We now create the configuration for the text classification pipeline we want to create.
    // Options to the pipeline can be set here using the Options field
    config := hugot.TextClassificationConfig{
        ModelPath: modelPath,
        Name:      "testPipeline",
    }
    // then we create out pipeline.
    // Note: the pipeline will also be added to the session object, so all pipelines can be destroyed at once
    sentimentPipeline, err := session.NewPipeline(config)
    check(err)

    // we can now use the pipeline for prediction on a batch of strings
    batch := []string{"This movie is disgustingly good !", "The director tried too much"}
    batchResult, err := sentimentPipeline.RunPipeline(ctx, batch)
    check(err)

    // and do whatever we want with it :)
    s, err := json.Marshal(batchResult)
    check(err)
    fmt.Println(string(s))
}
// OUTPUT: {"ClassificationOutputs":[[{"Label":"POSITIVE","Score":0.99031734}],[{"Label":"NEGATIVE","Score":0.963696}]]}

See also hugot_test.go for further examples for all pipelines.

Generative models

Hugot uses the Onnx Runtime Generative AI backend to run generative models.

Generative models are used in a variety of text and multimodal pipelines. Please look at the ORT text tests and ORT multimodal tests for examples of their usage.

To use the ORT Engine support for concurrent requests and inference batching (text-only messages), use the WithGenerativeEngine() option when creating a session.

Hardware acceleration 🚀

Hugot now also supports the following accelerator backends for your inference:

  • CUDA (tested on Onnx Runtime and XLA). See below for setup instructions.
  • TPU (XLA only)
  • TensorRT (available in Onnx Runtime only)
  • DirectML (available in Onnx Runtime only)
  • CoreML (available in Onnx Runtime only)
  • OpenVINO (available in Onnx Runtime only)

Please provide feedback if encountering any issues with the accelerators above!

To use Hugot with Nvidia gpu acceleration, you need to have the following:

  • The Nvidia driver for your graphics card (if running in Docker and WSL2, starting with --gpus all should inherit the drivers from the host OS)
  • ONNX Runtime:
    • The cuda gpu version of ONNX Runtime on the machine/docker container. You can see how we get that by looking at the Dockerfile. You can also get the ONNX Runtime libraries that we use for testing from the release. Just download the gpu .so libraries and put them in /usr/lib.
    • The required CUDA libraries installed on your system that are compatible with the ONNX Runtime gpu version you use. See here. For instance, for onnxruntime 1.28.0, we need CUDA 13.x (any minor version should be compatible) and cuDNN 9.x.
    • Start a session with the following:
      ctx := context.Background()
      opts := []options.WithOption{
        options.WithCuda(map[string]string{
          "device_id": "0",
        }),
      }
      session, err := NewORTSession(ctx, opts...)
      
  • OpenXLA
    • Install CUDA support via the command GOPROXY=direct go run github.com/gomlx/go-xla/cmd/pjrt_installer@latest -plugin=cuda13 -version=${JAX_CUDA_VERSION} -path=/usr/local/lib/go-xla
    • Start a session with the following:
      ctx := context.Background()
      opts := []options.WithOption{
        options.WithCuda(map[string]string{
          "device_id": "0",
        }),
      }
      session, err := NewXLASession(ctx, opts...)
      

For the ONNX Runtime Cuda libraries, you can install CUDA 13.x by installing the full cuda toolkit, but that's quite a big package. In our testing on awslinux/fedora, we have been able to limit the libraries needed to run Hugot with Nvidia gpu acceleration to just these:

  • cuda-cudart-13-3 libcublas-13-3 libcurand-13-3 libcufft-13-3 libcudnn9-cuda-13

libcufft and libcudnn9 are lazy loaded when needed, so may be skippable depending on the models you load.

On different distros (e.g. Ubuntu), you should be able to install the equivalent packages.

Training and fine-tuning pipelines

Hugot now also supports the training and fine-tuning of transformer pipelines! Training always runs through goMLX, on any backend: the onnx model is loaded into goMLX, fine-tuned, and serialized back to onnx format.

Go and XLA sessions (hugot.NewGoSession, hugot.NewXLASession) already run on goMLX, so they can train as they are, with no extra options. Only an ORT session needs something more: it has to be created with options.WithGoMLX() to train. Note that this changes the whole session, not just the trainer: every pipeline in a WithGoMLX session runs through goMLX rather than native ONNX Runtime. If you also want native ORT inference, use a separate session for training.

A trainer always loads its own copy of the model, so training never changes the weights of a pipeline you are serving, even in the same session. To serve the fine-tuned model, save it with trainer.Save and load the saved path like any other model.

Training is supported for the FeatureExtractionPipeline, the TextClassificationPipeline and the TokenClassificationPipeline (see text classifiers and token classifiers). The feature extraction pipeline can be used to fine-tune the vector embeddings for e.g. semantic textual similarity (for applications like RAG and semantic search). In order to fine-tune the feature extraction pipeline for semantic search you will need to collect a training dataset in the following format:

{"sentence1": "The quick brown fox jumps over the lazy dog", "sentence2": "A quick brown fox jumps over a lazy dog", "score": 1}
{"sentence1": "The quick brown fox jumps over the lazy dog", "sentence2": "A quick brown cow jumps over a lazy caterpillar", "score": 0.5}

See the example for a sample dataset.

The score is assumed to be a float between 0 and 1 that encodes the semantic similarity between the sentences, and by default a cosine similarity loss is used (see sentence transformers). You can specify a different optimizer or loss function from goMLX using the GOMLXOptions field of TrainerConfig.

Scored pairs are rare in practice. More often you have matching pairs: a query and the passage that answers it, a question and its duplicate. For those, use a ContrastiveDataset, which trains with in-batch negatives (sentence-transformers' MultipleNegativesRankingLoss): each anchor must pick out its own positive from all the positives in its batch. No scores are needed, and an optional hard negative per example makes the task harder and the embeddings sharper:

{"anchor": "how do I reset my password?", "positive": "To reset your password, open Settings and choose Security.", "negative": "Your password must be at least 12 characters long."}
dataset, err := datasets.NewContrastiveDataset(ctx, "pairs.jsonl", 32, nil, nil)

Larger batches give more negatives and usually better embeddings. Avoid duplicate pairs within a batch, which the loss would push apart. The defaults are AdamW at 2e-5 with weight decay 0.01 and a similarity scale of 20, as in sentence-transformers. With an evaluation dataset, the trainer records the in-batch retrieval accuracy per epoch.

A trainer is created from a session, in the same way as a pipeline:

// Training runs through goMLX on every backend. A Go or XLA session needs nothing extra;
// an ORT session must be created with options.WithGoMLX().
// NewXLASession requires the go build tags "XLA" or "ALL".
session, err := hugot.NewXLASession(ctx)
// To train on an Nvidia GPU, enable CUDA on the session:
// session, err := hugot.NewXLASession(ctx, options.WithCuda(nil))
check(err)
defer func() { _ = session.Destroy() }()

dataset, err := datasets.NewSemanticSimilarityDataset(ctx, "dataset.jsonl", 32, nil, nil)
check(err)

trainer, err := session.NewTrainer(
    hugot.TrainerConfig[*pipelines.FeatureExtractionPipeline]{
        ModelPath:    modelPath,
        TrainDataset: dataset,
        Verbose:      true,
    },
    hugot.WithEpochs(2),
)
check(err)
defer func() { _ = trainer.Close() }()

check(trainer.Train(ctx))
check(trainer.Save(ctx, outputPath))

Besides WithEpochs (default 100), the following trainer options are available:

  • WithEarlyStopping() / WithEarlyStoppingParams(patience, tolerance): stop when the loss on TrainerConfig.EvalDataset stops improving (defaults: patience 3, tolerance 1e-4). Requires EvalDataset to be set.
  • WithFreezeLayers(layers): freeze the given transformer layers (0 is the first); []int{-1} freezes every layer except the last.
  • WithFreezeEmbeddings(): freeze the embedding layers.

Set TrainerConfig.TrainEvalDataset to record a per-epoch training loss, available from trainer.Statistics() and written to statistics.txt on save.

trainer.Close() releases the trainer's copy of the model once you have saved it; a trainer that is never closed is released by session.Destroy(), so in a long-lived session that trains repeatedly, close each trainer when you are done with it. The fine-tuned model is written back as onnx, together with the tokenizer files and a statistics.txt holding the per-epoch losses, so the output directory can be loaded straight back into a pipeline.

Note that training on GPU is currently much faster and memory efficient than training on CPU, although optimizations are underway. On CPU, we recommend smaller batch sizes.

See the training tests for an example on how to fine-tune semantic similarity starting with an open source sentence transformers model and a few examples.

Fine-tuning a text classifier

A TextClassificationPipeline model, such as any Hugging Face ...ForSequenceClassification export, can be fine-tuned on labelled text. Labels are given by name and must be names in the model's id2label map (in its config.json). For single-label classification each line has one label:

{"text": "The film was a delight.", "label": "POSITIVE"}
{"text": "Two hours I will never get back.", "label": "NEGATIVE"}

and for multi-label classification each line has a list of labels, which may be empty:

{"text": "Late, and the wrong size.", "labels": ["delivery", "sizing"]}
dataset, err := datasets.NewTextClassificationDataset(ctx, "train.jsonl", 16, datasets.SingleLabel, nil, nil)
trainer, err := session.NewTrainer(hugot.TrainerConfig[*pipelines.TextClassificationPipeline]{
	ModelPath:        modelPath,
	TrainDataset:     dataset,
	TrainEvalDataset: evalDataset, // optional: loss and accuracy per epoch in trainer.Statistics()
}, hugot.WithEpochs(3))
err = trainer.Train(ctx)
err = trainer.Save(ctx, "fine-tuned-model") // load it with a TextClassificationPipeline as usual

Single-label training uses softmax cross-entropy and multi-label training a per-label sigmoid cross-entropy. With an evaluation dataset, the trainer records the accuracy and the macro-F1 per epoch (EpochTrainF1, EpochEvalF1). Prefer the macro-F1 on imbalanced data, where accuracy hides a missed minority class. For a full per-class report on any model, use evaluation.EvaluateTextClassification, or evaluation.ScoreClassification / ScoreMultiLabel on labels you already have. The default optimizer is AdamW with a learning rate of 5e-5 and a weight decay of 0.01; set GOMLXOptions to change either. When an evaluation dataset is given, the trainer records the loss and accuracy of every epoch. Save copies config.json with the model, so the saved classifier keeps its labels. Training a classifier from a model that has no classification head is not supported yet.

Prodigy annotations. The dataset also reads text classification exports from Prodigy, mixed freely with the format above:

{"text": "Late, and the wrong size.", "accept": ["delivery", "sizing"], "answer": "accept"}   // choice (textcat.manual)
{"text": "The film was a delight.", "label": "NEGATIVE", "answer": "reject"}               // binary (textcat.teach)

A choice annotation gives the chosen labels; a single-label dataset needs exactly one (annotate with --exclusive). A binary annotation says whether one label applies. Accepting a label makes it the class. Rejecting it only says what the text is not: for a two-class model that is the other class, and with more classes the example is skipped. A multi-label model can train on binary annotations only when it has that one label, because the other labels' values are unknown; otherwise use choice annotations. ignore answers and rejected choice annotations are skipped. evaluation.EvaluateTextClassification reads these examples the same way.

Fine-tuning a token classifier (NER)

A TokenClassificationPipeline model, such as any ...ForTokenClassification export, can be fine-tuned on sentences split into words, with one tag per word. Tags are names in the model's id2label map, for NER usually IOB tags:

{"tokens": ["EU", "rejects", "German", "call"], "tags": ["B-ORG", "O", "B-MISC", "O"]}
dataset, err := datasets.NewTokenClassificationDataset(ctx, "train.jsonl", 16, nil, nil)
trainer, err := session.NewTrainer(hugot.TrainerConfig[*pipelines.TokenClassificationPipeline]{
	ModelPath:    modelPath,
	TrainDataset: dataset,
}, hugot.WithEpochs(3))

The model labels sub-word tokens, so each word's tag is assigned to its first token. The remaining tokens of a word, the special tokens and the padding are left out of the loss and the accuracy, as in Hugging Face's NER fine-tuning. The defaults are the same as for text classification (AdamW, softmax cross-entropy).

With a TrainEvalDataset or EvalDataset, the trainer records two metrics per epoch: the accuracy per tagged word, and the entity-level F1 (EpochTrainF1, EpochEvalF1). Entity F1 is the usual NER metric: an entity counts only if its type and its full span are both right. Word accuracy is dominated by O tags, so prefer the F1. To score any model, including a saved one, use the evaluation package:

report, err := evaluation.EvaluateTokenClassification(ctx, pipeline, examples, 32)
fmt.Println(report.F1, report.PerType["PER"].Precision, report.PerType["PER"].Recall)

Scoring follows seqeval and conlleval. evaluation.ScoreEntities scores any pair of IOB tag sequences.

Custom word boundaries. The tags belong to words, so the model only works if inference splits text into the same words as the training data. When the split follows rules of its own (say Row7 becomes Row and 7, while 14C stays whole), write it once as a pipelines.WordSplitter and give it to both sides with pipelines.WithWordSplitter. Training examples can then be raw text, which the dataset splits with the trainer's pipeline:

{"text": "EU rejects German call", "tags": ["B-ORG", "O", "B-MISC", "O"]}
splitWords := []hugot.TokenClassificationOption{pipelines.WithWordSplitter(mySplitter)}
trainer, err := session.NewTrainer(hugot.TrainerConfig[*pipelines.TokenClassificationPipeline]{
	ModelPath:       modelPath,
	TrainDataset:    dataset,
	PipelineOptions: splitWords,
}, hugot.WithEpochs(3))
// ... train and save, then load the fine-tuned model with the same option:
pipeline, err := session.NewPipeline(hugot.TokenClassificationConfig{ModelPath: savePath, Name: "ner", Options: splitWords})
result, err := pipeline.RunPipeline(ctx, []string{"EU rejects German call"}) // labels the splitter's words

An example with both text and tokens is checked: the splitter's words must equal the tokens, which catches a pre-split file that no longer matches the rules. The splitter is code, not part of the saved model, so pass it wherever the model is loaded.

Span annotations (Prodigy). Examples can also be given as character spans, in the format Prodigy's ner_manual recipe exports, and both formats can be mixed in one file:

{"text": "Anna Weber visited Zürich", "spans": [{"start": 0, "end": 10, "label": "PER"}, {"start": 19, "end": 25, "label": "LOC"}], "answer": "accept"}

Spans are converted to word tags: B-PER I-PER O B-LOC. The words come from the pipeline's word splitter when one is set, and every span must then start and end on its word boundaries, so training sees exactly the words inference will. Without a splitter, the example's Prodigy tokens are the words, and inference must then be given the same words with RunWords. Offsets count characters, as Prodigy does, not bytes. Only examples answered accept (or with no answer) are used; reject and ignore are skipped. Each label needs its B- and I- forms in the model's id2label map.

Performance Tuning

Firstly, the throughput depends largely on the size of the input requests. The best batch size is affected by the number of tokens per input, but we find batches of roughly 32 inputs per call to be a good starting point.

ONNX Runtime

The library defaults to ONNX Runtime's default tuning settings. These are optimised for latency over throughput, and will attempt to parallelize single threaded calls to ONNX Runtime over multiple cores.

For maximum throughput, it is best to call a single shared Hugot pipeline from multiple goroutines (1 per core), using a channel to pass the input data. In this scenario, the following settings will greatly increase inference throughput.

session, err := hugot.NewORTSession(
	context.Background(),
	hugot.WithInterOpNumThreads(1),
	hugot.WithIntraOpNumThreads(1),
	hugot.WithCpuMemArena(false),
	hugot.WithMemPattern(false),
)

InterOpNumThreads and IntraOpNumThreads constricts each goroutine's call to a single core, greatly reducing locking and cache penalties. Disabling CpuMemArena and MemPattern skips pre-allocation of some memory structures, increasing latency, but also throughput efficiency.

File Systems

Hugot uses the standard operating system filesystem by default. File operations are defined by fileutil.FileSystem, which can be replaced with an adapter for an object store or another filesystem. Pass the adapter with options.WithFileSystem when creating a session; the adapter is scoped to that session and can be used safely by concurrent sessions:

session, err := hugot.NewGoSession(
    context.Background(),
    options.WithFileSystem(myFileSystemAdapter),
)
if err != nil {
    return err
}
defer session.Destroy()

The adapter must implement the operations in util/fileutil/file.go (OpenFile, CopyFile, Walk, DeleteFile, FileExists, FileStats, and NewFileWriter). This keeps Hugot independent of storage providers while allowing integrations such as afs or gocloud to translate those operations to their own APIs.

Limitations

Apart from the fact that only the aforementioned pipelines are currently implemented, the current limitations are:

  • the library is only built/tested on amd64-linux currently.

Contributing

If you would like to contribute to Hugot, please see the contribution guidelines.

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func ClosePipeline deprecated added in v0.3.3

func ClosePipeline[_ backends.Pipeline](s *Session, name string) error

ClosePipeline removes the pipeline with the given name from the session, tearing down the underlying model when no other pipeline depends on it.

Deprecated: use Session.ClosePipeline instead. This function is retained for backwards compatibility and will be removed in a future major release.

func DownloadModel ¶ added in v0.2.0

func DownloadModel(ctx context.Context, modelName string, destination string, options DownloadOptions) (string, error)

DownloadModel can be used to download a model directly from huggingface. Before the model is downloaded, validation occurs to ensure there is an .onnx and tokenizers.json file. Hugot only works with onnx models.

func GetPipeline deprecated added in v0.0.9

func GetPipeline[T backends.Pipeline](s *Session, name string) (T, error)

GetPipeline can be used to retrieve a pipeline of type T with the given name from the session.

Deprecated: use Session.GetPipeline instead. This function is retained for backwards compatibility and will be removed in a future major release.

func GetPipelines deprecated added in v0.7.3

func GetPipelines[T backends.Pipeline](s *Session) (map[string]T, error)

GetPipelines returns all pipelines of type T currently held by the session, keyed by name.

Deprecated: use Session.GetPipelines instead. This function is retained for backwards compatibility and will be removed in a future major release.

func NewPipeline deprecated added in v0.0.9

func NewPipeline[T backends.Pipeline](s *Session, pipelineConfig backends.PipelineConfig[T]) (T, error)

NewPipeline can be used to create a new pipeline of type T. The initialised pipeline will be returned and it will also be stored in the session object so that all created pipelines can be destroyed with session.Destroy() at once.

Deprecated: use Session.NewPipeline instead. This function is retained for backwards compatibility and will be removed in a future major release.

func ValidateDownloadedHFModel ¶ added in v0.7.3

func ValidateDownloadedHFModel(repo *hub.Repo, options DownloadOptions) ([]string, error)

Types ¶

type AddressParseConfig ¶ added in v0.8.3

type AddressParseOption ¶ added in v0.8.3

func WithAddressParseBatchSize ¶ added in v0.8.3

func WithAddressParseBatchSize(size int) AddressParseOption

WithAddressParseBatchSize limits addresses processed in one inference batch.

func WithAddressParseHyphenSplit ¶ added in v0.8.3

func WithAddressParseHyphenSplit() AddressParseOption

WithAddressParseHyphenSplit enables AddressParse's leading unit/street-number hyphen split, for example "3-305 Main Street" -> "3 305 Main Street".

func WithAddressParseManifestFilename ¶ added in v0.8.3

func WithAddressParseManifestFilename(filename string) AddressParseOption

WithAddressParseManifestFilename selects a manifest relative to the model directory.

func WithAddressParsePreprocessors ¶ added in v0.8.3

func WithAddressParsePreprocessors(processors ...AddressParsePreprocessor) AddressParseOption

WithAddressParsePreprocessors applies custom address transformations in order.

func WithAddressParseProbabilities ¶ added in v0.8.3

func WithAddressParseProbabilities(enabled bool) AddressParseOption

WithAddressParseProbabilities controls whether word scores are included.

func WithAddressParseProbabilityRounding ¶ added in v0.8.3

func WithAddressParseProbabilityRounding(digits int) AddressParseOption

WithAddressParseProbabilityRounding rounds included word scores. Use -1 to disable rounding.

type AddressParsePreprocessor ¶ added in v0.8.3

type AddressParsePreprocessor = pipelines.AddressParsePreprocessor

type AnyToAnyConfig ¶ added in v0.8.4

type AnyToAnyOption ¶ added in v0.8.4

type AudioClassificationConfig ¶ added in v0.8.1

type AudioClassificationConfig = backends.PipelineConfig[*pipelines.AudioClassificationPipeline]

type AudioClassificationOption ¶ added in v0.8.1

type AudioClassificationOption = backends.PipelineOption[*pipelines.AudioClassificationPipeline]

type AutomaticSpeechRecognitionConfig ¶ added in v0.8.1

type AutomaticSpeechRecognitionConfig = backends.PipelineConfig[*pipelines.AutomaticSpeechRecognitionPipeline]

type AutomaticSpeechRecognitionOption ¶ added in v0.8.1

type AutomaticSpeechRecognitionOption = backends.PipelineOption[*pipelines.AutomaticSpeechRecognitionPipeline]

type BackgroundRemovalConfig ¶ added in v0.8.1

type BackgroundRemovalConfig = backends.PipelineConfig[*pipelines.BackgroundRemovalPipeline]

type BackgroundRemovalOption ¶ added in v0.8.1

type BackgroundRemovalOption = backends.PipelineOption[*pipelines.BackgroundRemovalPipeline]

type CrossEncoderConfig ¶ added in v0.5.0

type CrossEncoderOption ¶ added in v0.5.0

type DepthEstimationConfig ¶ added in v0.8.1

type DepthEstimationConfig = backends.PipelineConfig[*pipelines.DepthEstimationPipeline]

type DepthEstimationOption ¶ added in v0.8.1

type DepthEstimationOption = backends.PipelineOption[*pipelines.DepthEstimationPipeline]

type DocumentQuestionAnsweringConfig ¶ added in v0.8.1

type DocumentQuestionAnsweringConfig = backends.PipelineConfig[*pipelines.DocumentQuestionAnsweringPipeline]

type DocumentQuestionAnsweringOption ¶ added in v0.8.1

type DocumentQuestionAnsweringOption = backends.PipelineOption[*pipelines.DocumentQuestionAnsweringPipeline]

type DownloadOptions ¶ added in v0.0.7

type DownloadOptions struct {
	AuthToken             string
	OnnxFilePath          string
	ExternalDataPath      string
	Branch                string
	MaxRetries            int
	RetryInterval         int
	ConcurrentConnections int
	Verbose               bool
	AdditionalFilePaths   []string
	// DownloadGraphBundle collects every artifact beside the selected graph and
	// in its subdirectories, including child graphs and external weights. It
	// implies PreservePaths. Select a specific variant with OnnxFilePath.
	DownloadGraphBundle bool
	PreservePaths       bool
	CacheDir            string
}

DownloadOptions is a struct of options that can be passed to DownloadModel.

func NewDownloadOptions ¶ added in v0.0.7

func NewDownloadOptions() DownloadOptions

NewDownloadOptions creates new DownloadOptions struct with default values. Override the values to specify different download options.

type FeatureExtractionConfig ¶ added in v0.0.9

type FeatureExtractionConfig = backends.PipelineConfig[*pipelines.FeatureExtractionPipeline]

type FeatureExtractionOption ¶ added in v0.1.1

type FeatureExtractionOption = backends.PipelineOption[*pipelines.FeatureExtractionPipeline]

type FillMaskConfig ¶ added in v0.8.1

type FillMaskOption ¶ added in v0.8.1

type GOMLXTrainingOptions ¶ added in v0.4.0

type GOMLXTrainingOptions struct {
	Optimizer optimizer.Interface
	Loss      loss.LossFn
}

GOMLXTrainingOptions overrides the optimizer and loss function used for training.

type GroundedObjectDetectionConfig ¶ added in v0.8.3

type GroundedObjectDetectionConfig = backends.PipelineConfig[*pipelines.GroundedObjectDetectionPipeline]

type GroundedObjectDetectionOption ¶ added in v0.8.3

type GroundedObjectDetectionOption = backends.PipelineOption[*pipelines.GroundedObjectDetectionPipeline]

type ImageClassificationConfig ¶ added in v0.5.0

type ImageClassificationConfig = backends.PipelineConfig[*pipelines.ImageClassificationPipeline]

type ImageClassificationOption ¶ added in v0.5.0

type ImageClassificationOption = backends.PipelineOption[*pipelines.ImageClassificationPipeline]

type ImageFeatureExtractionConfig ¶ added in v0.8.1

type ImageFeatureExtractionConfig = backends.PipelineConfig[*pipelines.ImageFeatureExtractionPipeline]

type ImageFeatureExtractionOption ¶ added in v0.8.1

type ImageFeatureExtractionOption = backends.PipelineOption[*pipelines.ImageFeatureExtractionPipeline]

type ImageSegmentationConfig ¶ added in v0.8.1

type ImageSegmentationConfig = backends.PipelineConfig[*pipelines.ImageSegmentationPipeline]

type ImageSegmentationOption ¶ added in v0.8.1

type ImageSegmentationOption = backends.PipelineOption[*pipelines.ImageSegmentationPipeline]

type ImageTextToTextConfig ¶ added in v0.8.1

type ImageTextToTextConfig = backends.PipelineConfig[*pipelines.ImageTextToTextPipeline]

type ImageTextToTextOption ¶ added in v0.8.1

type ImageTextToTextOption = backends.PipelineOption[*pipelines.ImageTextToTextPipeline]

type KeypointMatchingConfig ¶ added in v0.8.4

type KeypointMatchingConfig = backends.PipelineConfig[*pipelines.KeypointMatchingPipeline]

type KeypointMatchingOption ¶ added in v0.8.4

type KeypointMatchingOption = backends.PipelineOption[*pipelines.KeypointMatchingPipeline]

type MaskGenerationConfig ¶ added in v0.8.1

type MaskGenerationOption ¶ added in v0.8.1

type ObjectDetectionConfig ¶ added in v0.6.0

type ObjectDetectionConfig = backends.PipelineConfig[*pipelines.ObjectDetectionPipeline]

type ObjectDetectionOption ¶ added in v0.6.0

type ObjectDetectionOption = backends.PipelineOption[*pipelines.ObjectDetectionPipeline]

type Session ¶

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

Session allows for the creation of new pipelines and holds the pipeline already created.

func NewGoSession ¶ added in v0.4.0

func NewGoSession(ctx context.Context, opts ...options.WithOption) (*Session, error)

func NewORTSession ¶ added in v0.2.0

func NewORTSession(_ context.Context, _ ...options.WithOption) (*Session, error)

func NewXLASession ¶ added in v0.4.0

func NewXLASession(_ context.Context, _ ...options.WithOption) (*Session, error)

func (*Session) ClosePipeline ¶ added in v0.8.1

func (s *Session) ClosePipeline(name string) error

ClosePipeline removes the pipeline with the given name from the session, tearing down the underlying model when no other pipeline depends on it. Closing a name that is not registered is a no-op and returns nil.

err := session.ClosePipeline("name")

func (*Session) Destroy ¶

func (s *Session) Destroy() error

Destroy deletes the hugot session and onnxruntime environment and all initialized pipelines, freeing memory. A hugot session should be destroyed when not neeeded any more, preferably with a defer() call.

func (*Session) GetModels ¶ added in v0.7.3

func (s *Session) GetModels() map[string]*backends.Model

func (*Session) GetPipeline ¶ added in v0.8.1

func (s *Session) GetPipeline[T backends.Pipeline](name string) (T, error)

GetPipeline retrieves the pipeline of type T with the given name from the session.

example: pipeline, err := session.GetPipeline[*pipelines.TokenClassificationPipeline]("name")

func (*Session) GetPipelines ¶ added in v0.8.1

func (s *Session) GetPipelines[T backends.Pipeline]() (map[string]T, error)

GetPipelines returns all pipelines of type T currently held by the session, keyed by name.

example: pipelines, err := session.GetPipelines[*pipelines.TokenClassificationPipeline]()

func (*Session) GetStatistics ¶ added in v0.5.9

func (s *Session) GetStatistics() map[string]backends.PipelineStatistics

GetStatistics returns runtime statistics for all initialized pipelines for profiling purposes. We currently record for each pipeline: the total runtime of the tokenization step the number of batch calls to the tokenization step the average time per tokenization batch call the total runtime of the inference (i.e. onnxruntime) step the number of batch calls to the onnxruntime inference the average time per onnxruntime inference batch call.

func (*Session) NewPipeline ¶ added in v0.8.1

func (s *Session) NewPipeline[T backends.Pipeline](pipelineConfig backends.PipelineConfig[T]) (T, error)

NewPipeline creates a new pipeline of type T. The initialised pipeline is returned and is also stored in the session, so that all created pipelines can be destroyed together with Session.Destroy.

T is inferred from pipelineConfig, so no explicit type argument is needed:

pipeline, err := session.NewPipeline(config)

func (*Session) NewTrainer ¶ added in v0.8.1

func (s *Session) NewTrainer[T backends.Pipeline](config TrainerConfig[T], opts ...TrainerOption) (*Trainer[T], error)

NewTrainer creates a trainer for a pipeline of type T, fine-tuning the model at config.ModelPath on this session's backend.

T is inferred from config, so no explicit type argument is needed:

trainer, err := session.NewTrainer(hugot.TrainerConfig[*pipelines.FeatureExtractionPipeline]{
    ModelPath:    modelPath,
    TrainDataset: dataset,
}, hugot.WithEpochs(2))

Training runs on GoMLX for every backend. An ORT session must therefore be created with options.WithGoMLX; Go and XLA sessions need nothing extra.

The trainer always loads its own copy of the model, even when the session already has one for the same path: training writes to the model's weights, so sharing it would silently retrain any inference pipeline built on it. The copy is registered with the session under a private key, so no pipeline can ever reach it. Trainer.Close releases it; Session.Destroy releases any trainer left open. To serve the fine-tuned model, Trainer.Save it and load the saved path as usual.

func (*Session) PrintStatistics ¶ added in v0.5.9

func (s *Session) PrintStatistics()

PrintStatistics prints runtime statistics for all initialized pipelines to stdout.

type TableQuestionAnsweringConfig ¶ added in v0.8.1

type TableQuestionAnsweringConfig = backends.PipelineConfig[*pipelines.TableQuestionAnsweringPipeline]

type TableQuestionAnsweringOption ¶ added in v0.8.1

type TableQuestionAnsweringOption = backends.PipelineOption[*pipelines.TableQuestionAnsweringPipeline]

type TabularConfig ¶ added in v0.6.2

type TabularOption ¶ added in v0.6.2

type TextClassificationConfig ¶ added in v0.0.9

type TextClassificationConfig = backends.PipelineConfig[*pipelines.TextClassificationPipeline]

type TextClassificationOption ¶ added in v0.0.9

type TextClassificationOption = backends.PipelineOption[*pipelines.TextClassificationPipeline]

type TextGenerationConfig ¶ added in v0.5.0

type TextGenerationOption ¶ added in v0.5.0

type TextToAudioConfig ¶ added in v0.8.1

type TextToAudioOption ¶ added in v0.8.1

type TextToSpeechConfig ¶ added in v0.8.1

type TextToSpeechOption ¶ added in v0.8.1

type TokenClassificationConfig ¶ added in v0.0.9

type TokenClassificationConfig = backends.PipelineConfig[*pipelines.TokenClassificationPipeline]

type TokenClassificationOption ¶ added in v0.0.9

type TokenClassificationOption = backends.PipelineOption[*pipelines.TokenClassificationPipeline]

type Trainer ¶ added in v0.8.1

type Trainer[T backends.Pipeline] struct {
	// contains filtered or unexported fields
}

Trainer fine-tunes a pipeline of type T. It is created from a Session with Session.NewTrainer, and runs on that session's backend.

A Trainer is a single run: Train, then optionally Save, then Close. Close releases the trainer's private copy of the model; a trainer that is never closed is released by Session.Destroy. A Trainer is not safe for concurrent use.

func (*Trainer[T]) Close ¶ added in v0.8.1

func (t *Trainer[T]) Close() error

Close releases the trainer's copy of the model and removes it from the session. Save first if the fine-tuned model is wanted: after Close, Train and Save return an error. Close is safe to call more than once, and before or after Session.Destroy.

func (*Trainer[T]) Pipeline ¶ added in v0.8.1

func (t *Trainer[T]) Pipeline() T

Pipeline returns the pipeline being trained, typed as T.

func (*Trainer[T]) Save ¶ added in v0.8.1

func (t *Trainer[T]) Save(ctx context.Context, path string) (writeErr error)

Save writes the fine-tuned model to path as an ONNX model, alongside a statistics.txt holding the per-epoch losses. The model's config.json (which holds a classifier's labels) and its tokenizer files are copied from the original model directory.

func (*Trainer[T]) Statistics ¶ added in v0.8.1

func (t *Trainer[T]) Statistics() TrainingStatistics

Statistics returns the per-epoch losses recorded by the last call to Train.

func (*Trainer[T]) Train ¶ added in v0.8.1

func (t *Trainer[T]) Train(ctx context.Context) error

Train runs the training loop. The context cancels the run.

type TrainerConfig ¶ added in v0.8.1

type TrainerConfig[T backends.Pipeline] struct {
	// TrainDataset is the dataset to train on. Required.
	TrainDataset datasets.Dataset
	// TrainEvalDataset is evaluated after each epoch to record the training loss. Optional.
	TrainEvalDataset datasets.Dataset
	// EvalDataset is evaluated after each epoch to record the evaluation loss (and metrics), and
	// is what early stopping watches. Optional, but required by [WithEarlyStopping].
	EvalDataset datasets.Dataset
	// GOMLXOptions overrides the optimizer and loss function. Defaults are filled in per pipeline
	// type when nil.
	GOMLXOptions *GOMLXTrainingOptions
	// ModelPath is the directory holding the ONNX model to fine-tune. Required.
	ModelPath string
	// OnnxFilename names the ONNX file within ModelPath, when it cannot be inferred.
	OnnxFilename string
	// PipelineOptions configure the trainer's pipeline, which tokenizes the datasets and scores the
	// per-epoch metrics. Pass the options the fine-tuned model will run with at inference, e.g.
	// pipelines.WithWordSplitter, so training sees its inputs the same way.
	PipelineOptions []backends.PipelineOption[T]
	// Verbose prints progress to stdout during training.
	Verbose bool
}

TrainerConfig describes WHAT to train: a model and the data to train it on. How to train it is supplied separately as TrainerOption values, and where to run it is a property of the Session the trainer is created from.

type TrainerOption ¶ added in v0.8.1

type TrainerOption func(*trainerSettings) error

TrainerOption configures how a training run behaves.

func WithEarlyStopping ¶ added in v0.5.0

func WithEarlyStopping() TrainerOption

WithEarlyStopping enables early stopping with a patience of 3 epochs and a tolerance of 1e-4. It requires TrainerConfig.EvalDataset to be set.

func WithEarlyStoppingParams ¶ added in v0.5.0

func WithEarlyStoppingParams(patience int, tolerance float32) TrainerOption

WithEarlyStoppingParams enables early stopping with an explicit patience and tolerance. It requires TrainerConfig.EvalDataset to be set.

func WithEpochs ¶ added in v0.5.0

func WithEpochs(epochs int) TrainerOption

WithEpochs sets the maximum number of epochs to train for. Defaults to 100.

func WithFreezeEmbeddings ¶ added in v0.5.0

func WithFreezeEmbeddings() TrainerOption

WithFreezeEmbeddings freezes the embedding layers of the transformer model.

func WithFreezeLayers ¶ added in v0.5.0

func WithFreezeLayers(layers []int) TrainerOption

WithFreezeLayers freezes the given transformer layers. 0 is the first layer; the single value -1 freezes every layer apart from the last.

type TrainingStatistics ¶ added in v0.5.0

type TrainingStatistics struct {
	EpochTrainLosses []float32 `json:"epochTrainLosses"` // training loss for each epoch
	EpochEvalLosses  []float32 `json:"epochEvalLosses"`  // evaluation loss for each epoch
	// EpochTrainAccuracies and EpochEvalAccuracies hold the accuracy for each epoch, on the same
	// datasets as the losses: per example for text classification, per tagged word for token
	// classification. Recorded for classification pipelines only.
	EpochTrainAccuracies []float32 `json:"epochTrainAccuracies,omitempty"`
	EpochEvalAccuracies  []float32 `json:"epochEvalAccuracies,omitempty"`
	// EpochTrainF1 and EpochEvalF1 hold the F1 for each epoch, computed by running the model on the
	// datasets: entity-level F1 for token classification (see evaluation.ScoreEntities) and macro-F1
	// for text classification (see evaluation.ScoreMultiLabel). Recorded for those pipelines only.
	EpochTrainF1 []float32 `json:"epochTrainF1,omitempty"`
	EpochEvalF1  []float32 `json:"epochEvalF1,omitempty"`
}

TrainingStatistics holds the per-epoch losses recorded during a training run.

type VideoClassificationConfig ¶ added in v0.8.4

type VideoClassificationConfig = backends.PipelineConfig[*pipelines.VideoClassificationPipeline]

type VideoClassificationOption ¶ added in v0.8.4

type VideoClassificationOption = backends.PipelineOption[*pipelines.VideoClassificationPipeline]

type ZeroShotAudioClassificationConfig ¶ added in v0.8.1

type ZeroShotAudioClassificationConfig = backends.PipelineConfig[*pipelines.ZeroShotAudioClassificationPipeline]

type ZeroShotAudioClassificationOption ¶ added in v0.8.1

type ZeroShotAudioClassificationOption = backends.PipelineOption[*pipelines.ZeroShotAudioClassificationPipeline]

type ZeroShotClassificationConfig ¶ added in v0.1.4

type ZeroShotClassificationConfig = backends.PipelineConfig[*pipelines.ZeroShotClassificationPipeline]

type ZeroShotClassificationOption ¶ added in v0.3.0

type ZeroShotClassificationOption = backends.PipelineOption[*pipelines.ZeroShotClassificationPipeline]

type ZeroShotImageClassificationConfig ¶ added in v0.8.1

type ZeroShotImageClassificationConfig = backends.PipelineConfig[*pipelines.ZeroShotImageClassificationPipeline]

type ZeroShotImageClassificationOption ¶ added in v0.8.1

type ZeroShotImageClassificationOption = backends.PipelineOption[*pipelines.ZeroShotImageClassificationPipeline]

type ZeroShotObjectDetectionConfig ¶ added in v0.8.1

type ZeroShotObjectDetectionConfig = backends.PipelineConfig[*pipelines.ZeroShotObjectDetectionPipeline]

type ZeroShotObjectDetectionOption ¶ added in v0.8.1

type ZeroShotObjectDetectionOption = backends.PipelineOption[*pipelines.ZeroShotObjectDetectionPipeline]

Directories ¶

Path Synopsis
Package evaluation scores the predictions of fine-tuned pipelines.
Package evaluation scores the predictions of fine-tuned pipelines.
ort
util

Jump to

Keyboard shortcuts

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