Documentation
¶
Overview ¶
Package datasets is a collection of utility datasets (train.Dataset) that can be combined for efficient preprocessing: `Take`, `InMemory`, `Parallel`, `Map`, `MapOnHost`, `Freeing`.
It also includes normalization tools.
Index ¶
- func Batch(backend compute.Backend, ds train.Dataset, batchSize int, ...) train.Dataset
- func Const(batch train.Batch) train.Dataset
- func Map(backend compute.Backend, dataset train.Dataset, mapFn MapFn) train.Dataset
- func MapOnHost(ds train.Dataset, mapFn MapOnHostFn) train.Dataset
- func ModelMap(backend compute.Backend, store *model.Store, dataset train.Dataset, ...) train.Dataset
- func Normalization(backend compute.Backend, ds train.Dataset, inputsIndex int, ...) (mean, stddev *tensors.Tensor, err error)
- func ReadAhead(ds train.Dataset, bufferSize int) train.Datasetdeprecated
- func ReplaceZerosByOnes(x *graph.Node) *graph.Node
- func Take(ds train.Dataset, n int) train.Dataset
- func Zero() train.Dataset
- type BufferDataset
- type DistributedAccumulator
- func (ds *DistributedAccumulator) DeviceAssignment() []compute.DeviceNum
- func (ds *DistributedAccumulator) DistributedIter() iter.Seq2[train.DistributedBatch, error]
- func (ds *DistributedAccumulator) Iter() iter.Seq2[train.Batch, error]
- func (ds *DistributedAccumulator) Name() string
- func (ds *DistributedAccumulator) Stats() map[string]int
- func (ds *DistributedAccumulator) StatsString() string
- func (ds *DistributedAccumulator) Strategy() distributed.Strategy
- type GraphBatch
- type InMemoryDataset
- func GobDeserializeInMemoryToDevice(backend compute.Backend, deviceNum compute.DeviceNum, decoder *gob.Decoder) (mds *InMemoryDataset, err error)
- func InMemory(backend compute.Backend, ds train.Dataset, dsIsBatched bool) (mds *InMemoryDataset, err error)
- func InMemoryFromData(backend compute.Backend, name string, inputs []any, labels []any) (mds *InMemoryDataset, err error)
- func (mds *InMemoryDataset) BatchSize(n int, dropIncompleteBatch bool) *InMemoryDataset
- func (mds *InMemoryDataset) ByteSize() int64
- func (mds *InMemoryDataset) Copy() *InMemoryDataset
- func (mds *InMemoryDataset) FinalizeAll()
- func (mds *InMemoryDataset) GobSerialize(encoder *gob.Encoder) (err error)
- func (mds *InMemoryDataset) Infinite(infinite bool) *InMemoryDataset
- func (mds *InMemoryDataset) Iter() iter.Seq2[train.Batch, error]
- func (mds *InMemoryDataset) Name() string
- func (mds *InMemoryDataset) NumExamples() int
- func (mds *InMemoryDataset) RandomWithReplacement() *InMemoryDataset
- func (mds *InMemoryDataset) Reset()
- func (mds *InMemoryDataset) SetName(name string, shortName ...string) *InMemoryDataset
- func (mds *InMemoryDataset) ShortName() string
- func (mds *InMemoryDataset) Shuffle() *InMemoryDataset
- func (mds *InMemoryDataset) TakeN(n int) *InMemoryDataset
- func (mds *InMemoryDataset) WithRand(rng *rand.Rand) *InMemoryDataset
- func (mds *InMemoryDataset) WithSpec(spec any) *InMemoryDataset
- type MapFn
- type MapOnHostFn
- type ModelMapFn
- type OnDevice
- type ParallelMapDataset
- func (ds *ParallelMapDataset) Iter() iter.Seq2[train.Batch, error]
- func (ds *ParallelMapDataset) Name() string
- func (ds *ParallelMapDataset) ShortName() string
- func (ds *ParallelMapDataset) WithParallelism(parallelism int) *ParallelMapDataset
- func (ds *ParallelMapDataset) WithPreserveOrder(preserveOrder bool) *ParallelMapDataset
- type ParallelMapOnHostDataset
- func (ds *ParallelMapOnHostDataset) Iter() iter.Seq2[train.Batch, error]
- func (ds *ParallelMapOnHostDataset) Name() string
- func (ds *ParallelMapOnHostDataset) ShortName() string
- func (ds *ParallelMapOnHostDataset) WithParallelism(parallelism int) *ParallelMapOnHostDataset
- func (ds *ParallelMapOnHostDataset) WithPreserveOrder(preserveOrder bool) *ParallelMapOnHostDataset
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Batch ¶
func Batch( backend compute.Backend, ds train.Dataset, batchSize int, createLeadingAxis, dropIncompleteBatch bool, ) train.Dataset
Batch creates dataset that batches `ds` into batches of size `batchSize`.
It uses GoMLX to batch the tensors themselves, so it takes a graph.Backend as its first parameter. Also, it means that it yields examples already stored "on device" -- whichever the platform Backend was configured with.
Typically, Batch can benefit from ReadAhead, so while training or evaluation of batch is happening, the next batch is being built. Consider using ReadAhead on the Batch dataset, even with a buffer of only 1.
Args:
- `backend`: will be used to create the graph that actually does the batching.
- `ds`: the dataset to be batched.
- `batch_size`: size of each batch, except when there are no more examples, in which case batches can be smaller (except if `dropIncompleteBatch` was selected).
- `createLeadingAxis`: usually set to true, it will create a new leading axis that becomes the batch dimension. Otherwise, it simply concatenates the individual results at the axis 0 -- this can be used for instance to increase the size of a batch.
- `dropIncompleteBatch`: at the end of an epoch, if there are not enough examples to fill a batch, and this is set to true, the last batch is dropped. Otherwise, it returns only a partial batch -- with a different shape this may trigger the re-compilation of a graph. Usually desirable for evaluation, but not desirable for training.
Returns a `train.Dataset` that yields batched examples.
func Const ¶
Const returns a dataset that always yields a clone of the given batch, indefinitely.
Since batch ownership is transferred on yield, a clone of the batch is created on each iteration so that the original batch remains unchanged.
func Map ¶
Map returns a `train.Dataset` with the result of applying (mapping) the batches yielded by the provided `dataset` by the graph function `mapFn`. The function is executed by the `backend` given.
func MapOnHost ¶
func MapOnHost(ds train.Dataset, mapFn MapOnHostFn) train.Dataset
MapOnHost maps a dataset through a transformation with a (normal Go) function that runs in the host CPU.
func ModelMap ¶
func ModelMap(backend compute.Backend, store *model.Store, dataset train.Dataset, mapFn ModelMapFn) train.Dataset
ModelMap returns a `train.Dataset` with the result of applying (mapping) the batches yielded by the provided `dataset` by the graph function `mapFn` that can use trainable variables in the model store. The function is executed by the `backend` given. If `store` is nil, a new one is created.
func Normalization ¶
func Normalization(backend compute.Backend, ds train.Dataset, inputsIndex int, independentAxes ...int) (mean, stddev *tensors.Tensor, err error)
Normalization calculates the normalization parameters `mean` and `stddev` for the `inputsIndex`-th input from the given dataset.
These values can later be used for normalization by simply applying `Div(Sub(x, mean), stddev)`. To use as side inputs in an ML model, set them to variables.
The parameter `independentAxes` list axes that should not be normalized together. A typical value is -1, the feature axis (last axis), so that each feature gets its own normalization.
Notice for any feature that happens to be constant, the `stddev` will be 0. If trying to normalize (divide) by that will result in error. Use ReplaceZerosByOnes below to avoid the numeric issues.
func ReplaceZerosByOnes ¶
ReplaceZerosByOnes replaces any zero values in x by one. This is useful if normalizing a value with a standard deviation (`stddev`) that has zeros.
Types ¶
type BufferDataset ¶
type BufferDataset struct {
// contains filtered or unexported fields
}
BufferDataset is a wrapper around a `train.Dataset` that buffers (pre-fetches) batches in a background goroutine. This overlaps CPU data preparation with GPU/accelerator training.
func Buffer ¶
func Buffer(ds train.Dataset, bufferSize ...int) *BufferDataset
Buffer wraps a train.Dataset in a BufferDataset to prefetch yielded batches in a background goroutine.
If bufferSize is not specified, it defaults to 1.
The order of the batches returned by the underlying dataset is preserved.
func (*BufferDataset) ShortName ¶
func (bd *BufferDataset) ShortName() string
ShortName returns a short version of the dataset name, it implements train.HasShortName.
func (*BufferDataset) WithBufferSize ¶
func (bd *BufferDataset) WithBufferSize(size int) *BufferDataset
WithBufferSize configures the size of the prefetch queue (buffered channel) and returns the updated dataset.
type DistributedAccumulator ¶
type DistributedAccumulator struct {
// contains filtered or unexported fields
}
DistributedAccumulator is a dataset that is distributed across multiple devices, ready for distributed execution.
It accumulates the shards from the source dataset and yields them as a single dtensor.Tensor.
func NewDistributedAccumulator ¶
func NewDistributedAccumulator(backend compute.Backend, source train.Dataset, strategy distributed.Strategy, inputShardingSpecs, labelShardingSpecs []*distributed.ShardingSpec, deviceAssignment []compute.DeviceNum) ( *DistributedAccumulator, error)
NewDistributedAccumulator creates a distributed dataset from the given source dataset, by accumulating the shards and yielding them as a single dtensor.Tensor.
It uses the given strategy to distribute the data across the devices. The input and label sharding specs are used to specify how the data should be distributed.
deviceAssignment can be nil, in which case a default sequential assignment (starting from 0) is used.
The last element of inputShardingSpec is used if there are more inputs than specs defined. The same for labels.
func (*DistributedAccumulator) DeviceAssignment ¶
func (ds *DistributedAccumulator) DeviceAssignment() []compute.DeviceNum
DeviceAssignment implements train.DistributedDataset.
func (*DistributedAccumulator) DistributedIter ¶
func (ds *DistributedAccumulator) DistributedIter() iter.Seq2[train.DistributedBatch, error]
DistributedIter implements train.DistributedDataset.
func (*DistributedAccumulator) Name ¶
func (ds *DistributedAccumulator) Name() string
Name implements train.Dataset.
func (*DistributedAccumulator) Stats ¶
func (ds *DistributedAccumulator) Stats() map[string]int
Stats returns information on the number of source inputs of each shape/number seen so far.
func (*DistributedAccumulator) StatsString ¶
func (ds *DistributedAccumulator) StatsString() string
StatsString returns a pretty-print version of the statistics for debugging.
func (*DistributedAccumulator) Strategy ¶
func (ds *DistributedAccumulator) Strategy() distributed.Strategy
Strategy implements train.DistributedDataset.
type GraphBatch ¶
GraphBatch represents a batch of nodes in the graph building phase.
type InMemoryDataset ¶
type InMemoryDataset struct {
// contains filtered or unexported fields
}
InMemoryDataset represents a Dataset that has been completely read into the memory of the device it was created with -- the platform of the associated `graph.Backend`.
It supports batching, shuffling (with and without replacement) and can be duplicated (only one copy of the underlying data is used).
Finally, it supports serialization and deserialization, to accelerate loading of the data -- in case generating the original dataset is expensive (e.g: image transformations).
func GobDeserializeInMemoryToDevice ¶
func GobDeserializeInMemoryToDevice( backend compute.Backend, deviceNum compute.DeviceNum, decoder *gob.Decoder, ) (mds *InMemoryDataset, err error)
GobDeserializeInMemoryToDevice dataset from the decoder. It requires a `graph.Backend` and the deviceNum where the data is going to be stored -- it drops the local storage copy of the values.
No sampling configuration is recovered, and the InMemoryDataset created is sequential (no random sampling) that reads through only one epoch. The random number generator is also newly initialized (see InMemoryDataset.WithRand).
func InMemory ¶
func InMemory(backend compute.Backend, ds train.Dataset, dsIsBatched bool) (mds *InMemoryDataset, err error)
InMemory creates dataset that reads the whole contents of `ds` into memory.
It uses GoMLX to batch the tensors themselves, so it takes a graph.Backend as its first parameter. Flat will be cached in the platform (device) the Backend was configured with.
Args:
- `backend`: will be used to create the graph that does the caching and the ca actually does the batching.
- `ds`: dataset to be cached. It is read in full once, concatenating the results in the cache.
- `dsIsBatched`: whether the input `ds` is batched, and it's leading (first) axis is a batch size. If true, count of examples is adjusted accordingly. Notice if true, the batch size must be the same for all elements of the inputs and labels yielded by `ds`.
Returns a `InMemoryDataset`, that is initially not shuffled and not batched. You can configure how you want to use it with the other configuration methods.
func InMemoryFromData ¶
func InMemoryFromData( backend compute.Backend, name string, inputs []any, labels []any, ) (mds *InMemoryDataset, err error)
InMemoryFromData creates an InMemoryDataset from the static data given -- it is immediately converted to a tensor, if not a tensor already. The first dimension of each element of inputs and labels must be the batch size, and the same for every element.
This is useful to writing unit tests, with small datasets provided inline.
Example: A dataset with one input tensor and one label tensor. Each with two examples.
mds, err := InMemoryFromData(backend, "test",
[]any{[][]float32{{1, 2}, {3, 4}}},
[]any{[][]float32{{3}, {7}}})
func (*InMemoryDataset) BatchSize ¶
func (mds *InMemoryDataset) BatchSize(n int, dropIncompleteBatch bool) *InMemoryDataset
BatchSize configures the InMemoryDataset to return batches of the given size. dropIncompleteBatch is set to true, it will simply drop examples if there are not enough to fill a batch -- this can only happen on the last batch of an epoch. Otherwise, it will return a partially filled batch.
If `n` is set to 0, it reverts back to yielding one example at a time.
It returns the modified InMemoryDataset, so calls can be cascaded if one wants.
func (*InMemoryDataset) ByteSize ¶
func (mds *InMemoryDataset) ByteSize() int64
ByteSize returns an approximation of the memory being used.
func (*InMemoryDataset) Copy ¶
func (mds *InMemoryDataset) Copy() *InMemoryDataset
Copy returns a copy of the dataset. It uses the same underlying data -- so very little memory is used.
The copy comes configured by default with sequential reading (not random sampling), non-looping, and reset.
func (*InMemoryDataset) FinalizeAll ¶
func (mds *InMemoryDataset) FinalizeAll()
FinalizeAll will immediately free all the underlying data (and not wait for the garbage collector). This invalidates not only this InMemoryDataset, but also all other copies that use the same data (created with Copy).
This is not concurrency safe: if there are concurrent calls to sampling, this may lead to an undefined state or errors.
func (*InMemoryDataset) GobSerialize ¶
func (mds *InMemoryDataset) GobSerialize(encoder *gob.Encoder) (err error)
GobSerialize in-memory content to the encoder.
Only the underlying data is serialized. The graph.Backend or the sampling configuration is not serialized. The contents of the `spec` (see WithSpec) is also not serialized.
func (*InMemoryDataset) Infinite ¶
func (mds *InMemoryDataset) Infinite(infinite bool) *InMemoryDataset
Infinite sets whether the dataset should loop indefinitely. The default is `infinite = false`, which causes the dataset to going through the data only once before returning io.EOF.
It returns the modified InMemoryDataset, so calls can be cascaded if one wants.
func (*InMemoryDataset) Name ¶
func (mds *InMemoryDataset) Name() string
Name implements `train.Dataset`
func (*InMemoryDataset) NumExamples ¶
func (mds *InMemoryDataset) NumExamples() int
NumExamples cached.
func (*InMemoryDataset) RandomWithReplacement ¶
func (mds *InMemoryDataset) RandomWithReplacement() *InMemoryDataset
RandomWithReplacement configures the InMemoryDataset to return random elements with replacement. If this is configured, Shuffle is canceled.
It returns the modified InMemoryDataset, so calls can be cascaded if one wants.
func (*InMemoryDataset) Reset ¶
func (mds *InMemoryDataset) Reset()
Reset implements `train.Dataset`. It is a no-op since Iter() handles resetting dynamically per iteration.
func (*InMemoryDataset) SetName ¶
func (mds *InMemoryDataset) SetName(name string, shortName ...string) *InMemoryDataset
SetName sets the name of the dataset and optionally its ShortName, and returns the updated dataset.
func (*InMemoryDataset) ShortName ¶
func (mds *InMemoryDataset) ShortName() string
ShortName implements `train.HasShortName`
func (*InMemoryDataset) Shuffle ¶
func (mds *InMemoryDataset) Shuffle() *InMemoryDataset
Shuffle configures the InMemoryDataset to shuffle the order of the data. It returns random elements without replacement. If this is configured, RandomWithReplacement is canceled.
It returns the modified InMemoryDataset, so calls can be cascaded if one wants.
func (*InMemoryDataset) TakeN ¶
func (mds *InMemoryDataset) TakeN(n int) *InMemoryDataset
TakeN configures dataset to only take N examples before returning io.EOF. If set to 0 or -1, it takes as many as there is data. If configured, it automatically disables InMemoryDataset.Infinite
func (*InMemoryDataset) WithRand ¶
func (mds *InMemoryDataset) WithRand(rng *rand.Rand) *InMemoryDataset
WithRand sets the random number generator (RNG) for shuffling or random sampling. This allows for repeatable deterministic random sampling, if one wants. The default is to use an RNG initialized with the current nanosecond time.
It returns the modified InMemoryDataset, so calls can be cascaded if one wants.
func (*InMemoryDataset) WithSpec ¶
func (mds *InMemoryDataset) WithSpec(spec any) *InMemoryDataset
WithSpec sets the `spec` that is returned in Yield. The default is to use the one read from the original dataset passed to InMemory call. This allows one to set to something different.
It returns the modified InMemoryDataset, so calls can be cascaded if one wants.
type MapFn ¶
type MapFn func(graphBatch GraphBatch) GraphBatch
MapFn is a graph building function that transforms a GraphBatch.
type MapOnHostFn ¶
MapOnHostFn is a normal Go function that applies a transformation to the batch of a dataset on the host CPU.
Note: MapOnHostFn takes ownership of the incoming batch. Please manually finalize any input tensors that aren't reused in the output batch. Go's garbage collector will eventually free them, but since the GC doesn't track accelerator memory pressure, manual cleanup helps prevent out-of-memory errors.
type ModelMapFn ¶
type ModelMapFn func(scope *model.Scope, graphBatch GraphBatch) GraphBatch
ModelMapFn is a graph building function that transforms a GraphBatch using a model scope.
type OnDevice ¶
type OnDevice struct {
// contains filtered or unexported fields
}
OnDevice is a wrapper around a train.Dataset that yields tensors already on the target device.
It reads from the source dataset concurrently and uploads the data to the target device, keeping batches buffered in a channel so they're ready when Iter() is called.
func NewOnDevice ¶
func NewOnDevice(backend compute.Backend, source train.Dataset, bufferSize int, targetDevice compute.DeviceNum) (*OnDevice, error)
NewOnDevice creates a new OnDevice wrapper that wraps the source dataset and uploads batches to the target device.
- backend: the backend to use for device operations - source: the source dataset to read from. - bufferSize: size of the buffer channel (defaults to 1 if <= 0) - targetDevice: the target device number
type ParallelMapDataset ¶
type ParallelMapDataset struct {
// contains filtered or unexported fields
}
ParallelMapDataset implements a `train.Dataset` that maps a graph building function to a wrapped dataset in parallel.
func ParallelMap ¶
ParallelMap returns a `train.Dataset` with the result of applying (mapping) the batches yielded by the provided `dataset` by the graph function `mapFn` in parallel.
The default parallelism is the number of CPUs (runtime.NumCPU()), but it can be changed with WithParallelism(n).
The order of the batches returned by the underlying dataset is preserved by default, unless WithPreserveOrder(false) is called on the result.
func ParallelModelMap ¶
func ParallelModelMap(backend compute.Backend, store *model.Store, dataset train.Dataset, mapFn ModelMapFn) *ParallelMapDataset
ParallelModelMap returns a `train.Dataset` with the result of applying (mapping) the batches yielded by the provided `dataset` by the graph function `mapFn` that can use trainable variables in the model store, executed in parallel.
The default parallelism is the number of CPUs (runtime.NumCPU()), but it can be changed with WithParallelism(n).
The order of the batches returned by the underlying dataset is preserved by default, unless WithPreserveOrder(false) is called on the result.
If `store` is nil, a new one is created.
func (*ParallelMapDataset) Name ¶
func (ds *ParallelMapDataset) Name() string
Name implements train.Dataset.
func (*ParallelMapDataset) ShortName ¶
func (ds *ParallelMapDataset) ShortName() string
ShortName returns a short version of the dataset name, it implements train.HasShortName.
func (*ParallelMapDataset) WithParallelism ¶
func (ds *ParallelMapDataset) WithParallelism(parallelism int) *ParallelMapDataset
WithParallelism configures the number of parallel worker goroutines.
func (*ParallelMapDataset) WithPreserveOrder ¶
func (ds *ParallelMapDataset) WithPreserveOrder(preserveOrder bool) *ParallelMapDataset
WithPreserveOrder configures whether to preserve the original order of the batches. By default, it is enabled (true). Setting it to false allows out-of-order execution, which can improve performance/latency by avoiding re-ordering synchronization.
type ParallelMapOnHostDataset ¶
type ParallelMapOnHostDataset struct {
// contains filtered or unexported fields
}
ParallelMapOnHostDataset implements a `train.Dataset` that maps a function executed on the host CPU to a wrapped dataset in parallel.
func ParallelMapOnHost ¶
func ParallelMapOnHost(ds train.Dataset, mapFn MapOnHostFn) *ParallelMapOnHostDataset
ParallelMapOnHost maps a dataset through a transformation with a (normal Go) function that runs in the host CPU, executing the mapping function in parallel using the specified number of worker goroutines.
The default parallelism is the number of CPUs (runtime.NumCPU()), but it can be changed with WithParallelism(n).
The order of the batches returned by the underlying dataset is preserved by default, unless WithPreserveOrder(false) is called on the result.
func (*ParallelMapOnHostDataset) Name ¶
func (ds *ParallelMapOnHostDataset) Name() string
Name implements train.Dataset.
func (*ParallelMapOnHostDataset) ShortName ¶
func (ds *ParallelMapOnHostDataset) ShortName() string
ShortName returns a short version of the dataset name, it implements train.HasShortName.
func (*ParallelMapOnHostDataset) WithParallelism ¶
func (ds *ParallelMapOnHostDataset) WithParallelism(parallelism int) *ParallelMapOnHostDataset
WithParallelism configures the number of parallel worker goroutines.
func (*ParallelMapOnHostDataset) WithPreserveOrder ¶
func (ds *ParallelMapOnHostDataset) WithPreserveOrder(preserveOrder bool) *ParallelMapOnHostDataset
WithPreserveOrder configures whether to preserve the original order of the batches. By default, it is enabled (true). Setting it to false allows out-of-order execution, which can improve performance/latency by avoiding re-ordering synchronization.