Documentation
¶
Overview ¶
Package train holds tools to help run a training loop.
It provides various levels of tooling, from supporting training one step, or a full loop. But it should serve also as an example that users that needs more flexibility can start from to create their own training loops.
Index ¶
- Constants
- Variables
- func AddLoss(theLoss *graph.Node)deprecated
- func AddMainLoss(theLoss *graph.Node)
- func AddPerStepUpdateGraphFn(scope *model.Scope, g *graph.Graph, fn ModelGraphFn)
- func AddRegularizationLoss(theLoss *graph.Node)
- func EveryNSteps(loop *Loop, n int, name string, priority Priority, fn OnStepFn)
- func ExecPerStepUpdateGraphFn(g *graph.Graph)
- func ExponentialCallback(loop *Loop, startStep int, exponentialFactor float64, callOnEnd bool, ...)
- func GetLossNoRegularization(g *graph.Graph) (loss *graph.Node)deprecated
- func GetLosses(g *graph.Graph) (loss *graph.Node)deprecated
- func GetMainLoss(g *graph.Graph) (loss *graph.Node)
- func GetRegularizationLoss(g *graph.Graph) (loss *graph.Node)
- func GetTrainLastStepVar(g *graph.Graph) *model.Variable
- func NTimesDuringLoop(loop *Loop, n int, name string, priority Priority, fn OnStepFn)
- func PeriodicCallback(loop *Loop, period time.Duration, callOnEnd bool, name string, ...)
- func SetLossNoRegularization(theLoss *graph.Node)deprecated
- func TotalLoss(g *graph.Graph) (loss *graph.Node)
- type Batch
- type Dataset
- type DistributedBatch
- type DistributedDataset
- type GraphType
- type HasShortName
- type Loop
- func (loop *Loop) MedianTrainStepDuration() time.Duration
- func (loop *Loop) OnEnd(name string, priority Priority, fn OnEndFn)
- func (loop *Loop) OnFirstStep(name string, priority Priority, fn OnStepFn)
- func (loop *Loop) OnStart(name string, priority Priority, fn OnStartFn)
- func (loop *Loop) OnStep(name string, priority Priority, fn OnStepFn)
- func (loop *Loop) RunEpochs(ds Dataset, epochs int) (metrics []*tensors.Tensor, err error)
- func (loop *Loop) RunSteps(ds Dataset, steps int) (metrics []*tensors.Tensor, err error)
- func (loop *Loop) RunToGlobalStep(ds Dataset, targetGlobalStep int) (metrics []*tensors.Tensor, err error)
- type LossFn
- type ModelFn
- type ModelFnCompatible
- type ModelFnCompatibleOneOutput
- type ModelFnCompatibleSliceOutputs
- type ModelFnCompatibleThreeOutputs
- type ModelFnCompatibleTwoOutputs
- type ModelFnCompatibleZeroOutputs
- type ModelGraphFn
- type OnEndFn
- type OnExecFn
- type OnStartFn
- type OnStepFn
- type OptimizeWithGradients
- type Priority
- type Trainer
- func (r *Trainer) AccumulateGradients(numAccumulatingSteps int) error
- func (r *Trainer) Backend() compute.Backend
- func (r *Trainer) BatchNormalizationAveragesUpdate(ds Dataset) error
- func (r *Trainer) DistributedEval(ds DistributedDataset) (lossAndMetrics []*tensors.Tensor, err error)
- func (r *Trainer) DistributedEvalStep(strategy distributed.Strategy, deviceAssignment []compute.DeviceNum, ...) (metrics []*tensors.Tensor, err error)
- func (r *Trainer) DistributedTrainStep(strategy distributed.Strategy, deviceAssignment []compute.DeviceNum, ...) (metrics []*tensors.Tensor, err error)
- func (r *Trainer) Eval(ds Dataset) (lossAndMetrics []*tensors.Tensor, err error)
- func (r *Trainer) EvalMetrics() []metric.Interface
- func (r *Trainer) EvalStep(batch Batch) (metrics []*tensors.Tensor, err error)
- func (r *Trainer) GlobalStep() int64
- func (r *Trainer) Metrics() []metric.Interface
- func (r *Trainer) NumAccumulatingSteps() int
- func (r *Trainer) OnExecCreation(handler OnExecFn)
- func (r *Trainer) ResetComputationGraphs()
- func (r *Trainer) ResetTrainMetrics() error
- func (r *Trainer) SetStore(store *model.Store) *Trainer
- func (r *Trainer) Store() *model.Store
- func (r *Trainer) TrainMetrics() []metric.Interface
- func (r *Trainer) TrainStep(batch Batch) (metrics []*tensors.Tensor, err error)
- func (r *Trainer) WithDeviceAssignment(deviceAssignment ...compute.DeviceNum) *Trainer
- func (r *Trainer) WithInputsDynamicAxes(axisNames ...[]string) *Trainer
- func (r *Trainer) WithLabelsDynamicAxes(axisNames ...[]string) *Trainer
- func (r *Trainer) WithMainLossMetric() *Trainer
- func (r *Trainer) WithMaxExecutors(maxExecutors int) *Trainer
Constants ¶
const ( // TrainerAbsoluteScope used for Scope parameters related to the trainer. TrainerAbsoluteScope = model.ScopeSeparator + "trainer" // TrainerMainLossGraphParamKey is the graph params key that maps to the // node with the accumulated main losses in the model. TrainerMainLossGraphParamKey = "trainer_main_loss" // TrainerRegularizationLossGraphParamKey is the graph params key that maps to the // node with the accumulated regularization losses in the model. TrainerRegularizationLossGraphParamKey = "trainer_regularization_loss" // TrainerLossGraphParamKey is deprecated. // Deprecated: use TrainerMainLossGraphParamKey and TrainerRegularizationLossGraphParamKey instead. TrainerLossGraphParamKey = "trainer_loss" // TrainerLossNoRegularizationGraphParamKey is deprecated. // Deprecated: use TrainerMainLossGraphParamKey instead. TrainerLossNoRegularizationGraphParamKey = "trainer_loss_no_regularization" // TrainerPerStepUpdateGraphFnParamKey is used by AddPerStepUpdateGraphFn. TrainerPerStepUpdateGraphFnParamKey = "trainer_per_step_update_graph_fn" )
const AccumulatedGradientsScope = "acc_grads"
AccumulatedGradientsScope is the scope under which we accumulated gradients.
const ( // BatchNormalizationUpdatePhase is a graph parameter name used to indicate that the graph is only // running to update the mean/average parameters. See batchnorm.UpdateAveragesUpdate method. BatchNormalizationUpdatePhase = "batch_normalization_update_phase" )
const TrainLastStepVarName = "train_last_global_step"
TrainLastStepVarName is the name of the variable that holds the number of the target last GlobalStep. This variable is set by the Loop trainer, and may be -1 if the last train step is not known yet (for instance if using RunEpochs).
It is stored in the TrainerAbsoluteScope.
Variables ¶
var DefaultMaxExecutors = 50
DefaultMaxExecutors used for Trainer objects. Each different `spec` value from a Dataset triggers the creation of a new executor.
If using AccumulateGradients, there will be 2 graphs per shape of input data: one to accumulate the gradients and another to accumulate and apply the gradients.
Functions ¶
func AddLoss
deprecated
func AddMainLoss ¶ added in v0.28.0
AddMainLoss adds the given scalar loss to the trainer's Store as a main loss for the current graph. If another main loss has already been added, they are summed.
This is a global value for the Store, not scoped.
func AddPerStepUpdateGraphFn ¶
func AddPerStepUpdateGraphFn(scope *model.Scope, g *graph.Graph, fn ModelGraphFn)
AddPerStepUpdateGraphFn registers the given function fn to be executed at every training step.
func AddRegularizationLoss ¶ added in v0.28.0
AddRegularizationLoss adds the given scalar loss to the trainer's Store as a regularization loss for the current graph. If another regularization loss has already been added, they are summed.
This is a global value for the Store, not scoped.
func EveryNSteps ¶
EveryNSteps registers an OnStep hook on the loop that is called every N times.
Notice that it does not call `fn` at the last step (except if by coincidence).
func ExecPerStepUpdateGraphFn ¶ added in v0.17.1
ExecPerStepUpdateGraphFn executes all registered "per-step update functions".
The Store object will be read from the Graph.
func ExponentialCallback ¶ added in v0.4.0
func ExponentialCallback(loop *Loop, startStep int, exponentialFactor float64, callOnEnd bool, name string, priority Priority, fn OnStepFn)
ExponentialCallback registers an `OnStep` hook on the loop that is called at exponentially increasing number of steps in between, starting with startStep, and growing at geometric factor of exponentialFactor.
If callOnEnd is set, it will also call at the end of the loop.
Example: This will call at steps 100, 100+100*1.2 = 220, 220+100*1.2^2 = 364, ...
ExponentialCallback(loop, 100, 1.2, "my_callback", 100, myCallback)
func GetLossNoRegularization
deprecated
added in
v0.20.1
func GetMainLoss ¶ added in v0.28.0
GetMainLoss returns the sum of all main loss terms added with AddMainLoss(), or nil if none was set.
This is a global value for the Store, not scoped.
func GetRegularizationLoss ¶ added in v0.28.0
GetRegularizationLoss returns the sum of all regularization loss terms added with AddRegularizationLoss() (or the deprecated AddLoss()), or nil if none was set.
This is a global value for the Store, not scoped.
func GetTrainLastStepVar ¶ added in v0.13.0
GetTrainLastStepVar returns the variable that holds the number of the target last GlobalStep. This variable is set by the Loop trainer, and may be -1 if the last train step is not known yet (for instance if using RunEpochs).
The Store object will be read from the Graph.
It is stored in the TrainerAbsoluteScope.
This is a graph building function and so it may panic if the variable cannot be created.
func NTimesDuringLoop ¶
NTimesDuringLoop registers a OnStep hook on the loop that is called at most N times, split evenly across all steps.
For Loop.RunEpochs it does not work perfectly even, at least until it knows what is the exact number of steps -- it may even call OnStepFn more than n times.
It always calls `fn` at the very last step.
func PeriodicCallback ¶ added in v0.4.0
func PeriodicCallback(loop *Loop, period time.Duration, callOnEnd bool, name string, priority Priority, fn OnStepFn)
PeriodicCallback registers an `OnStep` hook on the loop that is called every period of time. The period counts after the execution of `OnStep`: this discounts the time to run `OnStep` (in case it is expensive) and it discounts cases where the execution is paused. By other hand, OnStep is not executed exactly at every `period` time.
If callOnEnd is set, it will also call at the end of the loop.
func SetLossNoRegularization
deprecated
added in
v0.20.1
Types ¶
type Batch ¶ added in v0.28.0
type Batch struct {
// Inputs and Labels of a batch, either are optional. The inputs are passed to the model function during training
// and evaluation. The labels are passed to the loss function(s) and metrics. The order must be agreed between the
// dataset and the model function that takes the inputs, and the loss/metric function for the loss(es) and
// metric(s).
//
// The Inputs and Labels ownership is transferred to the caller (usually a training or evaluation function). It's
// expected that they will be finalized immediately after use. This usually happens automatically if you use it
// with `train.Trainer` (it takes over the ownership).
//
// But if you are using the Batch yourself, remember to finalize the tensors (or call Batch.Finalize, it will
// do that for you).
Inputs, Labels []*tensors.Tensor
// Spec defines the task, configuration, or structural requirements
// for this specific batch. If this changes, GoMLX will generate
// and JIT-compile a new computation graph.
//
// This is used for multi-task training.
// If you are not using that, you can ignore it.
//
// For train.Trainer the Batch.Spec is converted to string as a key of a map[string] for different computation
// graphs, so each time the `spec` changes, the model graph is regenerated and re-compiled. Just like with
// Inputs or Labels of different shapes.
//
// Spec is assumed to be immutable, and ownership is not transferred.
Spec any
}
Batch represents one "item" yielded by a Dataset.
func (Batch) Clone ¶ added in v0.28.0
Clone returns a deep copy of the Batch. If any tensor clone fails, it returns the error.
type Dataset ¶
type Dataset interface {
// Name identifies the dataset. Used for debugging, pretty-printing and plots.
Name() string
// Iter returns an iterator over the dataset.
// It can be called multiple times (for example, to start a new epoch).
// It implicitly resets the dataset.
Iter() iter.Seq2[Batch, error]
}
Dataset for a train.Trainer provides the data, one batch at a time. Flat consists of a slice of *tensors.Tensor for `inputs` and for `labels`.
Dataset has to also provide a Dataset.Name() and a dataset `spec`, which usually is the same for the whole dataset, but can vary per batch, if the Dataset is yielding different types of data.
For a static Dataset that always provides the exact same data type, the `spec` can simply be nil.
Notice one batch (the unit of data) is represented by the Batch struct.
The Dataset interface allows for extensions/customizations by defining extra optional interfaces that a Dataset optionally can implement. See DistributedDataset.
type DistributedBatch ¶ added in v0.28.0
type DistributedBatch struct {
// Inputs and Labels of a batch, either are optional. They are sharded dtensor.Tensor instances.
// The inputs are passed to the model function during training and evaluation. The labels are
// passed to the loss function(s) and metrics.
//
// The Inputs and Labels ownership is transferred to the caller (usually a training or evaluation function).
// It's expected that they will be finalized immediately after use. This usually happens automatically
// if you use it with `train.Trainer` (it takes over the ownership).
//
// But if you are using the DistributedBatch yourself, remember to finalize the tensors (or call
// DistributedBatch.Finalize, it will do that for you).
Inputs, Labels []*dtensor.Tensor
// Spec defines the task, configuration, or structural requirements
// for this specific batch. If this changes, GoMLX will generate
// and JIT-compile a new computation graph.
Spec any
}
DistributedBatch represents one sharded batch of tensors yielded by a DistributedDataset.
func (DistributedBatch) Clone ¶ added in v0.28.0
func (b DistributedBatch) Clone() (DistributedBatch, error)
Clone returns a deep copy of the DistributedBatch. If any tensor clone fails, it returns the error.
func (DistributedBatch) Finalize ¶ added in v0.28.0
func (b DistributedBatch) Finalize() error
Finalize finalizes (frees) all tensors in the batch.
type DistributedDataset ¶ added in v0.28.0
type DistributedDataset interface {
// Dataset must also be implemented.
Dataset
// Strategy returns the distributed.Strategy to use for this dataset.
// Usually, distributed.AutoSharding. But distributed.SPMD (experimental) can also be used.
Strategy() distributed.Strategy
// DeviceAssignment returns the device assignment for the distributed dataset.
// The DistributedIter() method will return dtensor.Tensor already on the corresponding device.
DeviceAssignment() []compute.DeviceNum
// DistributedIter returns an iterator over the distributed dataset.
// It can be called multiple times (for example, to start a new epoch).
// It implicitly resets the dataset.
DistributedIter() iter.Seq2[DistributedBatch, error]
}
DistributedDataset is different API to a Dataset but yields dtensor.Tensors, ready for distributed execution.
An important aspect of the dataset is the distributed.ShardingSpec of each input and label. They are fed into the trainer to guide the distributed execution, and must remain the same for the same spec.
Note: if you need to control the device assignment, that is done in the Trainer.
A DistributedDataset implementation will usually also implement a Dataset interface, so it can be used with the Loop trainer.
type GraphType ¶ added in v0.4.1
type GraphType int
GraphType can be TrainGraph or EvalGraph, when there needs to be a distinction.
type HasShortName ¶ added in v0.23.0
type HasShortName interface {
// ShortName returns the short name of the dataset.
ShortName() string
}
HasShortName allows a dataset to specify a short name (used when displaying a short version of metric names). It defaults to the first 3 letters of the dataset name.
It's optional.
type Loop ¶
type Loop struct {
// Trainer associated with this loop. In particular Trainer.TrainMetrics() and
// Trainer.EvalMetrics() can be of interest.
// TODO: make Trainer an interface, so Loop can work on custom trainers..
Trainer *Trainer
// LoopStep currently being executed.
// It is initialized with the current store's `GlobalStep`, which will be 0 for a new model.
//
// Notice if using Trainer.AccumulateGradients: this is a measure of "train steps", and "global steps"
// will be incremented only every "numAccumulatedGradients" train steps are made.
LoopStep int
// StartStep is the value of LoopStep at the start of a run (RunSteps or RunEpochs).
//
// It is only set and valid during a run (Loop.RunSteps or Loop.RunEpochs).
StartStep int
// EndStep is one-past the last step to be executed. If -1 the end step is not known (if
// running till the end of the dataset). When running for multiple epochs (Loop.RunEpochs) it can
// change during the run (after the first epoch, the value is extrapolated based on how many steps
// have been run so far).
//
// It is only set and valid during a run (Loop.RunSteps or Loop.RunEpochs).
EndStep int
// Epoch is set when running Loop.RunEpochs() to the current running epoch, starting from 0.
Epoch int
// and semantics/type of their values are not specified by loop.
SharedData map[string]any
// trainStepDurations collected during training
TrainStepDurations []time.Duration
// contains filtered or unexported fields
}
Loop will run a training loop, invoking Trainer.TrainStep every step, and calling the appropriate hooks.
It also converts graph building errors thrown with `panic` and return them instead as normal errors.
By itself it doesn't do much, but one can attach functionality to it, like checkpointing, plotting tools, early-stopping strategies, etc. It is simple and flexible to allow arbitrary tools to the training loop.
The public attributes are meant for reading only, don't change them -- behavior can be undefined.
func (*Loop) MedianTrainStepDuration ¶ added in v0.4.0
MedianTrainStepDuration returns the median duration of each training step.
func (*Loop) OnEnd ¶
OnEnd adds a hook with given priority and name (for error reporting) to the end of a loop.
func (*Loop) OnFirstStep ¶ added in v0.28.30
OnFirstStep adds a hook with given priority and name (for error reporting) that is called only on the first step of the loop, and automatically deregisters itself afterward.
func (*Loop) OnStart ¶
OnStart adds a hook with given priority and name (for error reporting) to the start of a loop.
func (*Loop) OnStep ¶
OnStep adds a hook with given priority and name (for error reporting) to each step of a loop.
func (*Loop) RunEpochs ¶
RunEpochs runs those many steps. StartStep is adjusted to the current LoopStep, so it can be called multiple times, and it will simply pick up where it left of last time.
The returned `metrics` slice corresponds 1-to-1 with `loop.Trainer.TrainMetrics()` (index 0 is "Loss", index 1 is "Moving Average Loss", followed by custom trainMetrics).
func (*Loop) RunSteps ¶
RunSteps runs those many steps. StartStep and EndStep are adjusted to the current LoopStep, so it can be called multiple times, and it will simply pick up where it left of last time.
The returned `metrics` slice corresponds 1-to-1 with `loop.Trainer.TrainMetrics()` (index 0 is "Loss", index 1 is "Moving Average Loss", followed by custom trainMetrics).
func (*Loop) RunToGlobalStep ¶ added in v0.28.0
func (loop *Loop) RunToGlobalStep(ds Dataset, targetGlobalStep int) (metrics []*tensors.Tensor, err error)
RunToGlobalStep runs the loop until the target global step is reached. If targetGlobalStep is smaller than the current global step, it does nothing and returns nil metrics.
The returned `metrics` slice corresponds 1-to-1 with `loop.Trainer.TrainMetrics()` (index 0 is "Loss", index 1 is "Moving Average Loss", followed by custom trainMetrics).
type LossFn ¶
LossFn takes the output of ModelFn (called predictions, but it could be the logits), and the labels (coming out of Dataset.Yield()), and outputs the scalar loss, that can be used for training.
For some types of self-supervised models for which there are no labels, the labels can be empty.
Most of the predefined losses in package `gomlx/ml/train/losses` assume labels and predictions are both of length one. For multi-head models, it's very easy to write a small custom LossFn that splits the slice and send each label/prediction pair to a predefined loss.
Interface is defined in the losses package.
type ModelFn ¶
ModelFn is the canonical computation graph building function that takes as input a `spec` (given by the dataset) and a slice of `inputs` (even if just one) generated by a Dataset, and as output a slice (even if only one) of the `predictions` (or sometimes the logits).
The `predictions` output by ModelFn is fed to a LossFn and to MetricsFn during training.
Notice `spec` is opaque to train package, it's passed from the Dataset to the ModelFn, and its meaning is determined by the Dataset used. For static case (where data is always the same) it can simply be nil. Each value of `spec` is mapped to different computation graphs by the Trainer.
In most of the cases, on can instead simply use a ModelFnCompatible signature for the model function, and the NewTrainer will automatically wrap it and convert it to a ModelFn.
E.g.: A simple image classification modelFn that is ModelFnCompatible (single input, single output) and will automatically get converted to a ModelFn signature:
func MyImageClassificationModel(scope *model.Scope, image *graph.Node) (prediction *graph.Node)
type ModelFnCompatible ¶ added in v0.28.0
type ModelFnCompatible interface {
ModelFnCompatibleZeroOutputs |
ModelFnCompatibleOneOutput |
ModelFnCompatibleTwoOutputs |
ModelFnCompatibleThreeOutputs |
ModelFnCompatibleSliceOutputs
}
ModelFnCompatible represents a set of function signatures that are compatible aliases to the canonical ModelFn.
NewTrainer accepts any function matching this constraint and automatically wraps it to conform to the ModelFn signature.
Notice that the optional 'any' parameter in these signatures is always the opaque 'spec' parameter provided by datasets (usually only used for datasets with heterogeneous input data for multi-task training).
type ModelFnCompatibleOneOutput ¶ added in v0.28.0
type ModelFnCompatibleOneOutput interface {
~func(*model.Scope, *graph.Graph) *graph.Node |
~func(*model.Scope, *graph.Node) *graph.Node |
~func(*model.Scope, *graph.Node, *graph.Node) *graph.Node |
~func(*model.Scope, *graph.Node, *graph.Node, *graph.Node) *graph.Node |
~func(*model.Scope, []*graph.Node) *graph.Node |
~func(*model.Scope, any, *graph.Graph) *graph.Node |
~func(*model.Scope, any, *graph.Node) *graph.Node |
~func(*model.Scope, any, *graph.Node, *graph.Node) *graph.Node |
~func(*model.Scope, any, *graph.Node, *graph.Node, *graph.Node) *graph.Node |
~func(*model.Scope, any, []*graph.Node) *graph.Node
}
type ModelFnCompatibleSliceOutputs ¶ added in v0.28.0
type ModelFnCompatibleSliceOutputs interface {
~func(*model.Scope, *graph.Graph) []*graph.Node |
~func(*model.Scope, *graph.Node) []*graph.Node |
~func(*model.Scope, *graph.Node, *graph.Node) []*graph.Node |
~func(*model.Scope, *graph.Node, *graph.Node, *graph.Node) []*graph.Node |
~func(*model.Scope, []*graph.Node) []*graph.Node |
~func(*model.Scope, any, *graph.Graph) []*graph.Node |
~func(*model.Scope, any, *graph.Node) []*graph.Node |
~func(*model.Scope, any, *graph.Node, *graph.Node) []*graph.Node |
~func(*model.Scope, any, *graph.Node, *graph.Node, *graph.Node) []*graph.Node |
~func(*model.Scope, any, []*graph.Node) []*graph.Node
}
type ModelFnCompatibleThreeOutputs ¶ added in v0.28.0
type ModelFnCompatibleThreeOutputs interface {
~func(*model.Scope, *graph.Graph) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, []*graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Graph) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, any, []*graph.Node) (*graph.Node, *graph.Node, *graph.Node)
}
type ModelFnCompatibleTwoOutputs ¶ added in v0.28.0
type ModelFnCompatibleTwoOutputs interface {
~func(*model.Scope, *graph.Graph) (*graph.Node, *graph.Node) |
~func(*model.Scope, *graph.Node) (*graph.Node, *graph.Node) |
~func(*model.Scope, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
~func(*model.Scope, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
~func(*model.Scope, []*graph.Node) (*graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Graph) (*graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Node) (*graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Node, *graph.Node, *graph.Node) (*graph.Node, *graph.Node) |
~func(*model.Scope, any, []*graph.Node) (*graph.Node, *graph.Node)
}
type ModelFnCompatibleZeroOutputs ¶ added in v0.28.0
type ModelFnCompatibleZeroOutputs interface {
~func(*model.Scope, *graph.Graph) |
~func(*model.Scope, *graph.Node) |
~func(*model.Scope, *graph.Node, *graph.Node) |
~func(*model.Scope, *graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, []*graph.Node) |
~func(*model.Scope, any, *graph.Graph) |
~func(*model.Scope, any, *graph.Node) |
~func(*model.Scope, any, *graph.Node, *graph.Node) |
~func(*model.Scope, any, *graph.Node, *graph.Node, *graph.Node) |
~func(*model.Scope, any, []*graph.Node)
}
type ModelGraphFn ¶ added in v0.28.0
ModelGraphFn is a generic graph building function that takes a model scope (which points to its model.Store).
type OnEndFn ¶
OnEndFn is the type of OnEnd hooks. The `metrics` slice passed to the hook corresponds 1-to-1 with `loop.Trainer.TrainMetrics()`. Index 0 is the current batch's "Loss", index 1 is the "Moving Average Loss", and subsequent indices correspond to custom `trainMetrics` passed to `train.NewTrainer`.
type OnExecFn ¶ added in v0.4.1
OnExecFn is a handler that can be called when executors are created.
type OnStepFn ¶
OnStepFn is the type of OnStep hooks. The `metrics` slice passed to the hook corresponds 1-to-1 with `loop.Trainer.TrainMetrics()`. Index 0 is the current batch's "Loss", index 1 is the "Moving Average Loss", and subsequent indices correspond to custom `trainMetrics` passed to `train.NewTrainer`.
type OptimizeWithGradients ¶ added in v0.20.1
type OptimizeWithGradients interface {
// UpdateGraphWithGradients works like Optimizers.Interface.UpdateGraph, but takes as input the gradients themselves,
// as opposed to the loss.
UpdateGraphWithGradients(scope *model.Scope, gradients []*graph.Node, lossDType dtypes.DType)
}
OptimizeWithGradients is the interface an optimizer needs to support to be used with AccumulateGradients.
type Priority ¶
type Priority int
Priority for hooks, the lowest values are run first. Defaults to 0, but negative values are ok.
type Trainer ¶
type Trainer struct {
// contains filtered or unexported fields
}
Trainer is a helper object to orchestrate a training step and evaluation.
Given the inputs and labels, it deals with executing a training step (TrainStep) and evaluation (EvalStep and Eval), calling the loss and optimizer and running metrics.
See Loop for a flexible and extensible (different UIs) way to run this in a training loop.
func NewTrainer ¶
func NewTrainer[ModelFnT ModelFnCompatible](backend compute.Backend, store *model.Store, modelFn ModelFnT, lossFn LossFn, theOptimizer optimizer.Interface, trainMetrics, evalMetrics []metric.Interface) *Trainer
NewTrainer constructs a trainer that can be used for training steps and evaluation. It also creates a new Scope for model, which will hold the variables, hyperparameters, and other information. It can be changed by the user.
Its arguments are:
backend needed to create and compile computation graphs.
scope (will) hold the variables, hyperparameters, and related information for the model.
modelFn builds the graph that transforms inputs into predictions (or logits). It takes a ModelFn function or a function with a compatible signature, see the ModelFnCompatible constraint, that gets automatically converted to ModelFn (e.g., omitting the spec parameter, or returning 1-3 nodes).
lossFn takes the predictions (the output of modelFn) and the labels and outputs the loss. If the returned loss is not a scalar, it will be ReduceAllMean to a scalar. There are several standard losses available in gomlx/ml/train/losses package. They can simply be used as is, or called by arbitrary custom losses. It can also be set to nil, if one is providing loss terms with `AddMainLoss` -- e.g.: for unsupervised training.
optimizer (e.g: optimizer.StochasticGradientDescent) is the methodology to improve the model variables (aka. parameters or weights) to minimize the loss (the output of lossFn), typically using gradient descent.
trainMetrics are output by trainer.TrainStep after each step. Here it's recommended to use moving average types of metrics, since the model is changing so a mean wouldn't make sense. The mean loss of the batch and a moving average of the loss is always included (the first two) by default. It's ok to be empty (nil).
evalMetrics are output by trainer.EvalStep and trainer.Eval. Here it's recommend to use mean metrics, since the model is presumably frozen, and it sees each example exactly once. The mean of the loss of the dataset is always provided as the first metric. It's ok to be empty (nil).
func (*Trainer) AccumulateGradients ¶ added in v0.20.1
AccumulateGradients configures the trainer to accumulate numAccumulatingSteps of gradients before actually applying them. globalStep will only be updated after numAccumulatingSteps are fed with Trainer.TrainStep.
Notice that setting this makes the concept of "TrainStep" and "GlobalStep" diverge: there will now be numAccumulatingSteps "train steps" per "global step".
func (*Trainer) BatchNormalizationAveragesUpdate ¶ added in v0.11.0
BatchNormalizationAveragesUpdate runs through the dataset ds twice, updating the running averages for mean and variance.
It's recommended one resets the batch normalization weights with layers.BatchNormalizationResetWeights before calling this function.
Usually this method is not used directly, instead use norm.UpdateBatchNormAverages.
DistributedDatasets are not accepted yet -- open an issue if you need it.
func (*Trainer) DistributedEval ¶ added in v0.28.0
func (r *Trainer) DistributedEval(ds DistributedDataset) (lossAndMetrics []*tensors.Tensor, err error)
DistributedEval returns the computation of loss and metrics over the given distributed dataset.
func (*Trainer) DistributedEvalStep ¶ added in v0.28.0
func (r *Trainer) DistributedEvalStep(strategy distributed.Strategy, deviceAssignment []compute.DeviceNum, batch DistributedBatch) (metrics []*tensors.Tensor, err error)
DistributedEvalStep runs one eval step and returns the metrics, in a distributed fashion.
The DistributedBatch ownership (inputs/labels tensors) is transferred to the Trainer, which will finalize them after the evaluation step is executed.
func (*Trainer) DistributedTrainStep ¶ added in v0.28.0
func (r *Trainer) DistributedTrainStep(strategy distributed.Strategy, deviceAssignment []compute.DeviceNum, batch DistributedBatch) (metrics []*tensors.Tensor, err error)
DistributedTrainStep runs one step and returns the metrics, in a distributed fashion.
The DistributedBatch ownership (inputs/labels tensors) is transferred to the Trainer, which will finalize them after the training step is executed.
func (*Trainer) EvalMetrics ¶
EvalMetrics returns the eval metrics objects: not the actual metric values, just the objects that implement them, holds their name and a default pretty-printing function.
func (*Trainer) EvalStep ¶
EvalStep runs one eval step and returns the metrics, the first one being the mean loss.
The Batch ownership (inputs/labels tensors) is transferred to the Trainer, which will finalize them after the evaluation step is executed.
func (*Trainer) GlobalStep ¶ added in v0.21.0
GlobalStep is an alias for optimizer.GetGlobalStep using Trainer.Scope().
func (*Trainer) Metrics ¶
Metrics return list of registered eval metrics, including the loss metric that is added automatically.
func (*Trainer) NumAccumulatingSteps ¶ added in v0.21.0
NumAccumulatingSteps return the number of accumulating steps, if AccumulateGradients is being used. Otherwise, it returns 0.
func (*Trainer) OnExecCreation ¶ added in v0.4.1
OnExecCreation registers a handler to be called each time an executor (`model.Exec`) is created by the trainer.
func (*Trainer) ResetComputationGraphs ¶ added in v0.13.0
func (r *Trainer) ResetComputationGraphs()
ResetComputationGraphs can be used during training in between steps to force the recreation of the computation graphs.
This is used if, for instance, the training has schedules where hyperparameters change (some variables are frozen) the computation graph needs to be updated accordingly.
see Loop.OnStep to schedule
func (*Trainer) ResetTrainMetrics ¶
ResetTrainMetrics call Metrics.Reset on all train metrics. Usually called before a training session.
func (*Trainer) SetStore ¶ added in v0.28.0
SetStore associates the given model.Store to the trainer.
Should be called before any calls to Train or Evaluate, otherwise the results are undefined.
func (*Trainer) Store ¶ added in v0.28.0
Store returns the current Store. See SetScope to change it.
func (*Trainer) TrainMetrics ¶
TrainMetrics returns the train metrics objects (not the actual values just the objects that implement them).
func (*Trainer) TrainStep ¶
TrainStep runs one step and returns the metrics.
The Batch ownership (inputs/labels tensors) is transferred to the Trainer, which will finalize them after the training step is executed.
func (*Trainer) WithDeviceAssignment ¶ added in v0.28.0
WithDeviceAssignemnt sets the backend device assignment to use.
This works for both distributed and normal (single device) training. The later uses only one device where to execute the training/evaluation steps.
A nil value (the default) is valid, in which case it uses the backend's default, which is usually simply the sequential devices starting from 0.
func (*Trainer) WithInputsDynamicAxes ¶ added in v0.28.0
WithInputsDynamicAxes configures the dynamic axes for the model inputs. Each slice in the axisNames parameter corresponds to an input parameter of the model graph.
By marking an axis as dynamic, the computation graph will be compiled once with a symbolic size (e.g., shapes.DynamicDim) for that dimension. During subsequent executions, the actual size of the dynamic dimension is resolved dynamically from the shape of the execution inputs, avoiding expensive graph re-compilations for different input shapes.
Dynamic axes configuration must be set before any training or evaluation step is executed, otherwise it will have no effect on already created executors.
Example usage:
trainer := train.NewTrainer(backend, store, modelFn, lossFn, opt, nil, nil).
WithInputsDynamicAxes([]string{"batch", ""})
func (*Trainer) WithLabelsDynamicAxes ¶ added in v0.28.0
WithLabelsDynamicAxes configures the dynamic axes for the model labels. Each slice in the axisNames parameter corresponds to a label parameter of the model graph.
By marking an axis as dynamic, the computation graph will be compiled once with a symbolic size (e.g., shapes.DynamicDim) for that dimension. During subsequent executions, the actual size of the dynamic dimension is resolved dynamically from the shape of the execution inputs, avoiding expensive graph re-compilations for different input shapes.
Dynamic axes configuration must be set before any training or evaluation step is executed, otherwise it will have no effect on already created executors.
Example usage:
trainer := train.NewTrainer(backend, store, modelFn, lossFn, opt, nil, nil).
WithLabelsDynamicAxes([]string{"batch"})
func (*Trainer) WithMainLossMetric ¶ added in v0.28.0
WithMainLossMetric configures the trainer to also include the "no-reg" loss metrics, showing the model loss without regularization.
func (*Trainer) WithMaxExecutors ¶ added in v0.21.0
WithMaxExecutors configure the Trainer to allow these many different executors to be created before failing.
One executor is created per each different shape of input, times one for training, and one for evaluation (if Trainer.Eval is being used). The default is DefaultMaxExecutors.
It returns the Trainer itself.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package losses have several standard losses that implement train.LossFn interface.
|
Package losses have several standard losses that implement train.LossFn interface. |
|
Package metrics holds a library of metrics and defines
|
Package metrics holds a library of metrics and defines |
|
Package optimizer implements a collection of ML optimizers that can be used by train.Trainer, or by themselves.
|
Package optimizer implements a collection of ML optimizers that can be used by train.Trainer, or by themselves. |
|
cosineschedule
Package cosineschedule implements a cosine annealing schedule for the learning rate.
|
Package cosineschedule implements a cosine annealing schedule for the learning rate. |