dataset

package
v0.28.44 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 24 Imported by: 3 modules, 13 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

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

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

func Const(batch train.Batch) train.Dataset

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

func Map(backend compute.Backend, dataset train.Dataset, mapFn MapFn) train.Dataset

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 ReadAhead deprecated

func ReadAhead(ds train.Dataset, bufferSize int) train.Dataset

ReadAhead returns a Dataset that reads bufferSize elements of the given `ds` so that when Yield is called, the results are immediate.

Deprecated: please use Buffer() instead.

func ReplaceZerosByOnes

func ReplaceZerosByOnes(x *graph.Node) *graph.Node

ReplaceZerosByOnes replaces any zero values in x by one. This is useful if normalizing a value with a standard deviation (`stddev`) that has zeros.

func Take

func Take(ds train.Dataset, n int) train.Dataset

Take returns a wrapper to `ds`, a `train.Dataset` that only yields `n` batches.

func Zero

func Zero() train.Dataset

Zero returns a dataset that always yields a batch with 0 scalar as input and labels.

This is useful when training something that generates its own inputs and labels -- like trying to approximate a function with another function.

It loops indefinitely.

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) Iter

func (bd *BufferDataset) Iter() iter.Seq2[train.Batch, error]

Iter implements train.Dataset.

func (*BufferDataset) Name

func (bd *BufferDataset) Name() string

Name implements train.Dataset.

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) Iter

Iter implements train.Dataset.

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

Strategy implements train.DistributedDataset.

type GraphBatch

type GraphBatch struct {
	Inputs, Labels []*graph.Node
	Spec           any
}

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) Iter

func (mds *InMemoryDataset) Iter() iter.Seq2[train.Batch, error]

Iter implements `train.Dataset`.

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

type MapOnHostFn func(batch train.Batch) train.Batch

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

func (*OnDevice) Iter

func (ds *OnDevice) Iter() iter.Seq2[train.Batch, error]

Iter implements train.Dataset.

func (*OnDevice) Name

func (ds *OnDevice) Name() string

Name implements train.Dataset.

func (*OnDevice) ShortName

func (ds *OnDevice) ShortName() string

ShortName implements train.HasShortName.

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

func ParallelMap(backend compute.Backend, dataset train.Dataset, mapFn MapFn) *ParallelMapDataset

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) Iter

Iter implements train.Dataset.

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) Iter

Iter implements train.Dataset.

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.

Jump to

Keyboard shortcuts

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