Documentation
¶
Index ¶
- func ClosePipeline[_ backends.Pipeline](s *Session, name string) errordeprecated
- func DownloadModel(ctx context.Context, modelName string, destination string, ...) (string, error)
- func GetPipeline[T backends.Pipeline](s *Session, name string) (T, error)deprecated
- func GetPipelines[T backends.Pipeline](s *Session) (map[string]T, error)deprecated
- func NewPipeline[T backends.Pipeline](s *Session, pipelineConfig backends.PipelineConfig[T]) (T, error)deprecated
- func ValidateDownloadedHFModel(repo *hub.Repo, options DownloadOptions) ([]string, error)
- type AddressParseConfig
- type AddressParseOption
- func WithAddressParseBatchSize(size int) AddressParseOption
- func WithAddressParseHyphenSplit() AddressParseOption
- func WithAddressParseManifestFilename(filename string) AddressParseOption
- func WithAddressParsePreprocessors(processors ...AddressParsePreprocessor) AddressParseOption
- func WithAddressParseProbabilities(enabled bool) AddressParseOption
- func WithAddressParseProbabilityRounding(digits int) AddressParseOption
- type AddressParsePreprocessor
- type AnyToAnyConfig
- type AnyToAnyOption
- type AudioClassificationConfig
- type AudioClassificationOption
- type AutomaticSpeechRecognitionConfig
- type AutomaticSpeechRecognitionOption
- type BackgroundRemovalConfig
- type BackgroundRemovalOption
- type CrossEncoderConfig
- type CrossEncoderOption
- type DecisionConfig
- type DecisionOption
- type DepthEstimationConfig
- type DepthEstimationOption
- type DocumentQuestionAnsweringConfig
- type DocumentQuestionAnsweringOption
- type DownloadOptions
- type FeatureExtractionConfig
- type FeatureExtractionOption
- type FillMaskConfig
- type FillMaskOption
- type GOMLXTrainingOptions
- type GroundedObjectDetectionConfig
- type GroundedObjectDetectionOption
- type ImageClassificationConfig
- type ImageClassificationOption
- type ImageFeatureExtractionConfig
- type ImageFeatureExtractionOption
- type ImageSegmentationConfig
- type ImageSegmentationOption
- type ImageTextToTextConfig
- type ImageTextToTextOption
- type KeypointMatchingConfig
- type KeypointMatchingOption
- type LearningRateDecay
- type LearningRateSchedule
- type MaskGenerationConfig
- type MaskGenerationOption
- type ObjectDetectionConfig
- type ObjectDetectionOption
- type Session
- func (s *Session) ClosePipeline(name string) error
- func (s *Session) Destroy() error
- func (s *Session) GetModels() map[string]*backends.Model
- func (s *Session) GetPipeline[T backends.Pipeline](name string) (T, error)
- func (s *Session) GetPipelines[T backends.Pipeline]() (map[string]T, error)
- func (s *Session) GetStatistics() map[string]backends.PipelineStatistics
- func (s *Session) NewPipeline[T backends.Pipeline](pipelineConfig backends.PipelineConfig[T]) (T, error)
- func (s *Session) NewTrainer[T backends.Pipeline](config TrainerConfig[T], opts ...TrainerOption) (*Trainer[T], error)
- func (s *Session) PrintStatistics()
- type TableQuestionAnsweringConfig
- type TableQuestionAnsweringOption
- type TabularConfig
- type TabularOption
- type TextClassificationConfig
- type TextClassificationOption
- type TextGenerationConfig
- type TextGenerationOption
- type TextToAudioConfig
- type TextToAudioOption
- type TextToSpeechConfig
- type TextToSpeechOption
- type TokenClassificationConfig
- type TokenClassificationOption
- type Trainer
- func (t *Trainer[T]) Close() error
- func (t *Trainer[T]) HeadChange() *backends.ClassifierHeadChange
- func (t *Trainer[T]) Pipeline() T
- func (t *Trainer[T]) Save(ctx context.Context, path string) (writeErr error)
- func (t *Trainer[T]) Statistics() TrainingStatistics
- func (t *Trainer[T]) Train(ctx context.Context) error
- type TrainerConfig
- type TrainerOption
- func WithEarlyStopping() TrainerOption
- func WithEarlyStoppingParams(patience int, tolerance float32) TrainerOption
- func WithEpochs(epochs int) TrainerOption
- func WithFreezeEmbeddings() TrainerOption
- func WithFreezeLayers(layers []int) TrainerOption
- func WithLearningRateSchedule(schedule LearningRateSchedule) TrainerOption
- func WithSeed(seed uint64) TrainerOption
- func WithoutShuffle() TrainerOption
- type TrainingStatistics
- type VideoClassificationConfig
- type VideoClassificationOption
- type ZeroShotAudioClassificationConfig
- type ZeroShotAudioClassificationOption
- type ZeroShotClassificationConfig
- type ZeroShotClassificationOption
- type ZeroShotImageClassificationConfig
- type ZeroShotImageClassificationOption
- type ZeroShotObjectDetectionConfig
- type ZeroShotObjectDetectionOption
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClosePipeline
deprecated
added in
v0.3.3
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
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
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 AddressParseConfig = backends.PipelineConfig[*pipelines.AddressParsePipeline]
type AddressParseOption ¶ added in v0.8.3
type AddressParseOption = backends.PipelineOption[*pipelines.AddressParsePipeline]
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 AnyToAnyConfig = backends.PipelineConfig[*pipelines.AnyToAnyPipeline]
type AnyToAnyOption ¶ added in v0.8.4
type AnyToAnyOption = backends.PipelineOption[*pipelines.AnyToAnyPipeline]
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 CrossEncoderConfig = backends.PipelineConfig[*pipelines.CrossEncoderPipeline]
type CrossEncoderOption ¶ added in v0.5.0
type CrossEncoderOption = backends.PipelineOption[*pipelines.CrossEncoderPipeline]
type DecisionConfig ¶ added in v0.8.6
type DecisionConfig = backends.PipelineConfig[*pipelines.DecisionPipeline]
type DecisionOption ¶ added in v0.8.6
type DecisionOption = backends.PipelineOption[*pipelines.DecisionPipeline]
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 FillMaskConfig = backends.PipelineConfig[*pipelines.FillMaskPipeline]
type FillMaskOption ¶ added in v0.8.1
type FillMaskOption = backends.PipelineOption[*pipelines.FillMaskPipeline]
type GOMLXTrainingOptions ¶ added in v0.4.0
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 LearningRateDecay ¶ added in v0.9.0
type LearningRateDecay int
LearningRateDecay is how the learning rate falls after the warmup.
const ( // LinearDecay lowers the rate in a straight line, from its peak at the end of the warmup to 0 at // the last step. It is the default of Hugging Face's Trainer. LinearDecay LearningRateDecay = iota // CosineDecay lowers the rate from its peak to 0 along half a cosine: slowly at first, fastest // halfway, and slowly again near the end. CosineDecay // ConstantRate keeps the rate at its peak after the warmup. ConstantRate )
func (LearningRateDecay) String ¶ added in v0.9.0
func (d LearningRateDecay) String() string
type LearningRateSchedule ¶ added in v0.9.0
type LearningRateSchedule struct {
// Decay after the warmup. The zero value is LinearDecay.
Decay LearningRateDecay
// WarmupRatio is the share of the run's steps spent warming up, in [0, 1). A few percent is
// usual: 0.06 to 0.1. Set at most one of WarmupRatio and WarmupSteps.
WarmupRatio float64
// WarmupSteps is the number of steps spent warming up.
WarmupSteps int
// PeakLearningRate is the rate at the end of the warmup. It replaces the optimizer's own rate.
// Left at 0, it is the trainer's default for the pipeline, which only applies when the trainer
// also builds the optimizer: with GOMLXTrainingOptions.Optimizer set, it is required.
PeakLearningRate float64
}
LearningRateSchedule sets how the learning rate changes over a training run: a linear warmup from 0 to PeakLearningRate, then a decay. It follows Hugging Face's schedules, step for step.
The schedule is laid over every step of the run, maxEpochs times the batches in one pass over the training dataset (see WithMaxEpochs). Early stopping ends the run before the rate has decayed all the way, as it does in Hugging Face.
type MaskGenerationConfig ¶ added in v0.8.1
type MaskGenerationConfig = backends.PipelineConfig[*pipelines.MaskGenerationPipeline]
type MaskGenerationOption ¶ added in v0.8.1
type MaskGenerationOption = backends.PipelineOption[*pipelines.MaskGenerationPipeline]
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 NewORTSession ¶ added in v0.2.0
func NewXLASession ¶ added in v0.4.0
func (*Session) ClosePipeline ¶ added in v0.8.1
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 ¶
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) GetPipeline ¶ added in v0.8.1
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
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 TabularConfig = backends.PipelineConfig[*pipelines.TabularPipeline]
type TabularOption ¶ added in v0.6.2
type TabularOption = backends.PipelineOption[*pipelines.TabularPipeline]
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 TextGenerationConfig = backends.PipelineConfig[*pipelines.TextGenerationPipeline]
type TextGenerationOption ¶ added in v0.5.0
type TextGenerationOption = backends.PipelineOption[*pipelines.TextGenerationPipeline]
type TextToAudioConfig ¶ added in v0.8.1
type TextToAudioConfig = backends.PipelineConfig[*pipelines.TextToAudioPipeline]
type TextToAudioOption ¶ added in v0.8.1
type TextToAudioOption = backends.PipelineOption[*pipelines.TextToAudioPipeline]
type TextToSpeechConfig ¶ added in v0.8.1
type TextToSpeechConfig = backends.PipelineConfig[*pipelines.TextToSpeechPipeline]
type TextToSpeechOption ¶ added in v0.8.1
type TextToSpeechOption = backends.PipelineOption[*pipelines.TextToSpeechPipeline]
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
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
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]) HeadChange ¶ added in v0.8.6
func (t *Trainer[T]) HeadChange() *backends.ClassifierHeadChange
HeadChange reports how TrainerConfig.Labels changed the model's classification head: whether a new head was created, and which labels were kept, added and removed. It is nil when TrainerConfig.Labels is empty.
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
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.
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 // Labels sets the labels a text or token classification model is trained to predict, in id // order. Leave it empty to train on the model's own id2label labels. // // When the model already has a classification head, it is resized to these labels: a label the // model already knows keeps its trained weights, a new label (e.g. a new entity tag such as // "B-PRODUCT") starts from fresh weights, and a label left out is dropped. When the model has no // head, e.g. a plain encoder such as all-MiniLM-L6-v2, a new one is added on top of it; for text // classification the encoder's hidden states are mean-pooled over the attention mask first. // [Trainer.Save] writes the labels into the saved config.json. // // To keep what the model already predicts, train on data that still contains its existing // labels, not only the new ones; otherwise it forgets them. Labels []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.
With early stopping, the trained model keeps the weights of its best epoch, the one with the lowest evaluation loss, rather than those of the last epoch trained: when training stops, or runs out of epochs, the best weights are restored. TrainingStatistics.BestEpoch reports which.
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 being the first. The single value -1 freezes the embeddings and every transformer layer but the last, so the last layer and any head on top of it train: the model adapts without losing what it learned in pretraining. Indices beyond the model's last layer are an error when training starts.
func WithLearningRateSchedule ¶ added in v0.9.0
func WithLearningRateSchedule(schedule LearningRateSchedule) TrainerOption
WithLearningRateSchedule warms the learning rate up and then decays it, rather than keeping it constant. Warming up protects the pretrained weights from the large, noisy gradients of a new or resized classification head in the first steps; decaying lets training settle at the end.
The training dataset must implement datasets.BatchCounter, as all of hugot's datasets do. For a .jsonl file, the trainer reads it once more at construction to count its examples.
func WithSeed ¶ added in v0.9.0
func WithSeed(seed uint64) TrainerOption
WithSeed sets the seed for shuffling the training data, so that runs can differ from one another or be reproduced. Defaults to 42.
func WithoutShuffle ¶ added in v0.9.0
func WithoutShuffle() TrainerOption
WithoutShuffle trains on the examples in the order the training dataset holds them, the same order every epoch. By default each epoch visits them in a new random order (see datasets.Shuffler), which helps whenever the data is sorted, e.g. grouped by label, and for a contrastive dataset gives each example new in-batch negatives every epoch.
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"`
// EpochRunningLosses holds, for each epoch, the mean loss over that epoch's training steps. It is
// recorded on every run at no extra cost, unlike EpochTrainLosses, which takes a separate pass
// over TrainerConfig.TrainEvalDataset. The weights change during the epoch, so it trails the
// loss the model has at the epoch's end.
EpochRunningLosses []float32 `json:"epochRunningLosses,omitempty"`
// EpochLearningRates holds, for each epoch, the learning rate of its last training step. It is
// recorded with a learning rate schedule only (see WithLearningRateSchedule).
EpochLearningRates []float32 `json:"epochLearningRates,omitempty"`
// BestEpoch is the epoch, counting from 1, whose weights the trained model holds when early
// stopping is enabled: the one with the lowest evaluation loss. It is 0 without early stopping,
// where the model holds the weights of the last epoch.
BestEpoch int `json:"bestEpoch,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]
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package evaluation scores the predictions of fine-tuned pipelines.
|
Package evaluation scores the predictions of fine-tuned pipelines. |
|
util
|
|